package com.gpframework.module.controller.order;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.domain.entity.SysDept;
import com.gpframework.common.core.domain.entity.SysRole;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.*;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.manufacture.domain.GpProductionApplication;
import com.gpframework.module.manufacture.domain.GpProductionDetails;
import com.gpframework.module.manufacture.domain.GpProductionFlow;
import com.gpframework.module.manufacture.domain.GpProductionScheduling;
import com.gpframework.module.manufacture.service.IGpProductionApplicationService;
import com.gpframework.module.manufacture.service.IGpProductionDetailsService;
import com.gpframework.module.manufacture.service.IGpProductionFlowService;
import com.gpframework.module.manufacture.service.IGpProductionSchedulingService;
import com.gpframework.module.module.domain.*;
import com.gpframework.module.module.service.*;
import com.gpframework.module.order.domain.*;
import com.gpframework.module.order.domain.req.*;
import com.gpframework.module.order.domain.vo.*;
import com.gpframework.module.order.service.*;
import com.gpframework.module.process.domain.*;
import com.gpframework.module.process.service.*;
import com.gpframework.module.purchase.domain.*;
import com.gpframework.module.purchase.service.*;
import com.gpframework.module.system.mapper.SysDeptMapper;
import com.gpframework.module.system.mapper.SysRoleMapper;
import com.gpframework.module.system.mapper.SysUserMapper;
import com.gpframework.module.system.mapper.SysUserRoleMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName GpOrderController
 * @Author gpframework
 * @Date 2024-4-25
 * @Version 1.0.0
 * @Description 销售单Controller 接口类
 */
@Validated
@Api(tags = "销售单")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
public class GpOrderController extends BaseController {

    /**
     * 销售单Service接口
     */
    private final IGpOrderService iGpOrderService;
    /**
     * 产品Service接口
     */
    private final IGpProductService gpProductService;
    /**
     * 员工订单流转详情Service接口
     */
    private final IGpOrderFlowService gpOrderFlowService;
    /**
     * 流转节点配置Service接口
     */
    private final IGpFlowConfigService gpFlowConfigService;
    /**
     * 流转节点角色关联Service接口
     */
    private final IGpFlowConfigRoleRelaService gpFlowConfigRoleRelaService;
    /**
     * 用户表Mapper
     */
    private final SysUserMapper sysUserMapper;
    /**
     * 用户与角色关联表Mapper
     */
    private final SysUserRoleMapper sysUserRoleMapper;
    /**
     * 角色表Mapper
     */
    private final SysRoleMapper sysRoleMapper;
    /**
     * 部门管理Mapper
     */
    private final SysDeptMapper sysDeptMapper;
    /**
     * 缺货报库存申请Service接口
     */
    private final IGpProductionApplicationService gpProductionApplicationService;
    /**
     * 做货明细Service接口
     */
    private final IGpProductionDetailsService gpProductionDetailsService;
    /**
     * 生产排单Service接口
     */
    private final IGpProductionSchedulingService gpProductionSchedulingService;
    /**
     * 到货单Service接口
     */
    private final IGpDeliveryNoteService gpDeliveryNoteService;
    /**
     * 来料检验单Service接口
     */
    private final IGpIncomingInspectService gpIncomingInspectService;
    /**
     * 品质反馈Service接口
     */
    private final IGpQualityfeedbackService gpQualityfeedbackService;
    /**
     * 品质问题跟踪明细Service接口
     */
    private final IGpQualityFlowDetailsService gpQualityFlowDetailsService;
    /**
     * 克重Service接口
     */
    private final IGpGramWeightService gpGramWeightService;
    /**
     * 色牢度Service接口
     */
    private final IGpColorFastnessService gpColorFastnessService;
    /**
     * 甲醛自测与送检机构数据对比Service接口
     */
    private final IGpFormaldehydeContrastService gpFormaldehydeContrastService;
    /**
     * 排单Service接口
     */
    private final IGpProcessSchedulingService gpProcessSchedulingService;
    /**
     * 加工到货单Service接口
     */
    private final IGpProcessDeliveryNoteService gpProcessDeliveryNoteService;
    /**
     * 加工来料检验单Service接口
     */
    private final IGpProcessIncomingInspectService gpProcessIncomingInspectService;
    /**
     * 溢码率Service接口
     */
    private final IGpProcessOverflowRateService gpProcessOverflowRateService;
    /**
     * 成本核算Service接口
     */
    private final IGpProcessCostingService gpProcessCostingService;
    /**
     * 生产跟踪Service接口
     */
    private final IGpProductionFlowService gpProductionFlowService;
    /**
     * 加工问题跟踪Service接口
     */
    private final IGpProcessProblemTrackService gpProcessProblemTrackService;
    /**
     * 甲醛自测与送检机构数据对比加工Service接口
     */
    private final IGpProcessFormaldehydeContrastService iGpProcessFormaldehydeContrastService;
    /**
     * 改标Service接口
     */
    private final IGpRevisionTableService iGpRevisionTableService;
    /**
     * 送检Service接口
     */
    private final IGpInspectionTableService iGpInspectionTableService;
    /**
     * 采购做货明细Service接口
     */
    private final IGpPurchasingMakingDetailsService iGpPurchasingMakingDetailsService;
    /**
     * 采购排单Service接口
     */
    private final IGpProcureSchedulingService iGpProcureSchedulingService;
    /**
     * 采购收货单Service接口
     */
    private final IGpPurchaseReceiptService iGpPurchaseReceiptService;
    /**
     * 采购跟踪单Service接口
     */
    private final IGpPurchaseTrackService iGpPurchaseTrackService;
    /**
     * 采购来料检验单Service接口
     */
    private final IGpPurchaseIncomingInspectService iGpPurchaseIncomingInspectService;
    /**
     * 采购品质反馈Service接口
     */
    private final IGpPurchaseQualityFeedbackService iGpPurchaseQualityFeedbackService;
    /**
     * 采购品质问题跟踪明细Service接口
     */
    private final IGpPurchaseQualityFlowDetailsService iGpPurchaseQualityFlowDetailsService;
    /**
     * 采购克重Service接口
     */
    private final IGpPurchaseGramWeightService iGpPurchaseGramWeightService;
    /**
     * 车次设置Service接口
     */
    private final IGpDestinationNoConfigService iGpDestinationNoConfigService;
    /**
     * 车次发车记录Service接口
     */
    private final IGpDestinationNoLogService iGpDestinationNoLogService;
    /**
     * 流转节点配置Service接口
     */
    private final IGpFlowConfigService iGpFlowConfigService;
    /**
     * 流转节点角色关联Service接口
     */
    private final IGpFlowConfigRoleRelaService iGpFlowConfigRoleRelaService;
    /**
     * 转发记录Service接口
     */
    private final IGpForwardLogService iGpForwardLogService;
    /**
     * 转发记录详情Service接口
     */
    private final IGpForwardLogDetailService iGpForwardLogDetailService;
    /**
     * 员工订单流转详情Service接口
     */
    private final IGpOrderFlowService iGpOrderFlowService;
    /**
     * 消息通知Service接口
     */
    private final IGpOrderNotifyService iGpOrderNotifyService;
    /**
     * 产品Service接口
     */
    private final IGpProductService iGpProductService;
    /**
     * 产品详情Service接口
     */
    private final IGpProductDetailsService iGpProductDetailsService;
    /**
     * 货架信息Service接口
     */
    private final IGpProductShelvesService iGpProductShelvesService;
    /**
     * 货架图片信息Service接口
     */
    private final IGpProductShelvesImgService iGpProductShelvesImgService;

    /** order begin **/

     /**
      * @Description 分页
      * @Author gpframework
      * @Date 2024-4-25
      * @Param gpOrder
      * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/order/list")
    public TableDataInfo<GpOrderVo> list(GpOrderReq gpOrderReq)
    {
        Long userId = gpOrderReq.getUserId();
        // 不查询暂停的订单
//        gpOrderReq.setIsSuspend(0);
        if (userId == null) {
            return getError("用户未登录");
        }
        QueryWrapper<GpOrder> lqw = new QueryWrapper<GpOrder>();
        gpOrderReq.generatorQuery(lqw,true);
        boolean confirmFlag = false;
        // 获取用户角色权限标识
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
        List<String> roleKeyList = sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        // 获取可进行流程流转操作的角色权限标识
        List<String> confirmRoleKeyList = RoleKeyEnum.confirmRoleKey();
        // 判断当前用户是否有可操作权限
        if (!CollectionUtils.isEmpty(roleKeyList) && !CollectionUtils.isEmpty(confirmRoleKeyList)) {
            roleKeyList.retainAll(confirmRoleKeyList);
            if (!CollectionUtils.isEmpty(roleKeyList)) {
                confirmFlag = true;
            }
        }
        if (confirmFlag) {
            List<Long> orderStatus = gpFlowConfigService.getOrderStatusByUserId(userId);
            if (StringUtils.equals(gpOrderReq.getOrderStatus(), OrderStatusEnum.IN_TRANSIT_DELIVERY.getKey()) && orderStatus.contains(30L)) {
                // 有中转权限才显示‘中转未处理’
                lqw.eq("gp.order_status", gpOrderReq.getOrderStatus());
            } else {
                // 40 表示已经完成的订单
                orderStatus.add(40L);
                lqw.in("gp.order_status", orderStatus);
                // 查询对应日期的数据
                if (gpOrderReq.getSearchDate() != null) {
                    if (StringUtils.equals(gpOrderReq.getSearchDateType(), "1")) {
                        lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
                    } else {
                        lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') < '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
                    }
                }
            }
            if (StringUtils.equals(gpOrderReq.getOrderByForward(), YesNoEnum.YES.getKey())) {
                // 分享页，先按是否分享排序再按订单号排序
                lqw.orderByAsc("gp.is_forward");
                lqw.orderByAsc("gp.form_code");
                // 分享页只显示有上传物流单的单子
                lqw.eq("gof.status", YesNoEnum.YES.getKey());
                lqw.in("gof.config_id", 3,4);
            } else {
                lqw.orderByDesc("gp.is_urgent");
                lqw.orderByAsc("gp.update_time");
            }
        } else {
            SysUser sysUser = sysUserMapper.selectUserById(userId);
            SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            if (!StringUtils.equals(gpOrderReq.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
                lqw.ne("gp.order_status" ,OrderStatusEnum.COMPLETE.getKey());
            }
            lqw.eq("gp.organise_unit", sysDept.getDeptName());
            // 如果是销售员(所有角色数据权限都是‘仅本人数据权限’)，查询销售员对应的订单
            List<SysRole> collect = sysRoles.stream().filter(role -> StringUtils.equals(role.getDataScope(), "5")).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect) && collect.size() == sysRoles.size()) {
                lqw.eq("gp.salesman", sysUser.getNickName());
            }
            if (StringUtils.equals(gpOrderReq.getOrderByForward(), YesNoEnum.YES.getKey())) {
                // 分享页，先按是否分享排序再按订单号排序
                lqw.orderByAsc("gp.is_forward");
                lqw.orderByAsc("gp.form_code");
                // 分享页只显示有上传物流单的单子
                lqw.eq("gof.status", YesNoEnum.YES.getKey());
                lqw.in("gof.config_id", 3,4);
            } else {
                lqw.orderByAsc("gp.form_code");
            }
            // 查询对应日期的数据
            if (gpOrderReq.getSearchDate() != null) {
                if (StringUtils.equals(gpOrderReq.getSearchDateType(), "1")) {
                    lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
                } else {
                    lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') < '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
                }
            }
        }
        lqw.eq("gp.is_cancel", YesNoEnum.NO.getKey());
        lqw.groupBy("gp.id");
        startPage();
        List<GpOrderVo> list = iGpOrderService.listVo(lqw);

        for (GpOrderVo gpOrderVo : list) {
            getOrderTime(gpOrderVo);
            this.getFlowStatus(gpOrderVo);
        }
        return getDataTable(list);
    }

    private void getFlowStatus(GpOrderVo gpOrderVo) {
        // 细码
        gpOrderVo.setFineCodeAnnexList(new ArrayList<>());
        String fineCodeStatus = gpOrderFlowService.getFlowStatus(new QueryWrapper<GpOrderFlow>()
                .eq("gp.del_status", YesNoEnum.NO.getKey())
                .eq("gp.order_id", gpOrderVo.getId())
                .eq("fc.sort", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey())
                .orderByDesc("gp.create_time")
                .last("limit 1"));
        if (StringUtils.isNotBlank(fineCodeStatus)) {
            gpOrderVo.setFineCodeStatus(fineCodeStatus);
            // 有图片并且订单完成的获取图片列表
            if (StringUtils.equals(fineCodeStatus, "1") && StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
                List<String> annexList = this.getAnnexList(gpOrderVo.getId(), "1");
                if (CollectionUtils.isNotEmpty(annexList)) {
                    gpOrderVo.setFineCodeAnnexList(annexList);
                }
            }
        } else {
            gpOrderVo.setFineCodeStatus(YesNoEnum.NO.getKey());
        }

        // 物流单
        gpOrderVo.setLogisticsOrderAnnexList(new ArrayList<>());
        String logisticsOrderStatus = gpOrderFlowService.getFlowStatus(new QueryWrapper<GpOrderFlow>()
                .eq("gp.del_status", YesNoEnum.NO.getKey())
                .eq("gp.order_id", gpOrderVo.getId())
                .eq("gp.destination_type", DestinationTypeEnum.LOGISTICS.getKey())
                .orderByDesc("gp.create_time")
                .last("limit 1"));
        if (StringUtils.isNotBlank(logisticsOrderStatus)) {
            gpOrderVo.setLogisticsOrderStatus(logisticsOrderStatus);
            // 有图片并且订单完成的获取图片列表
            if (StringUtils.equals(logisticsOrderStatus, "1") && StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
                List<String> annexList = this.getAnnexList(gpOrderVo.getId(), "2");
                if (CollectionUtils.isNotEmpty(annexList)) {
                    gpOrderVo.setLogisticsOrderAnnexList(annexList);
                }
            }
        } else {
            gpOrderVo.setLogisticsOrderStatus(YesNoEnum.NO.getKey());
        }

        // 自提
        String selfPickupStatus = gpOrderFlowService.getFlowStatus(new QueryWrapper<GpOrderFlow>()
                .eq("gp.del_status", YesNoEnum.NO.getKey())
                .eq("gp.order_id", gpOrderVo.getId())
                .eq("gp.destination_type", DestinationTypeEnum.SELF_PICKUP.getKey())
                .orderByDesc("gp.create_time")
                .last("limit 1"));
        if (StringUtils.isNotBlank(selfPickupStatus)) {
            gpOrderVo.setSelfPickupStatus(selfPickupStatus);
        } else {
            gpOrderVo.setSelfPickupStatus(YesNoEnum.NO.getKey());
        }
    }

    /**
      * @Description 查询各分类订单数量
      * @Author gpframework
      * @Date 2024-4-25
      * @Param gpOrder
      * @Return TableDataInfo
     */
    @ApiOperation("查询各分类订单数量")
    @GetMapping("/order/order/getCount")
    public AjaxResult getCount(GpOrderReq gpOrderReq)
    {
        Map<String, Object> j = new HashMap<>();
        Long userId = gpOrderReq.getUserId();
        // 不查询暂停的订单
//        gpOrderReq.setIsSuspend(0);
        if (userId == null) {
            return AjaxResult.error("用户未登录");
        }
        boolean confirmFlag = false;
        // 获取用户角色权限标识
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
        List<String> roleKeyList = sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        // 获取可进行流程流转操作的角色权限标识
        List<String> confirmRoleKeyList = RoleKeyEnum.confirmRoleKey();
        // 判断当前用户是否有可操作权限
        if (!CollectionUtils.isEmpty(roleKeyList) && !CollectionUtils.isEmpty(confirmRoleKeyList)) {
            roleKeyList.retainAll(confirmRoleKeyList);
            if (!CollectionUtils.isEmpty(roleKeyList)) {
                confirmFlag = true;
            }
        }
        // 今日待处理
        QueryWrapper<GpOrder> todayPendingProcessingLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayPendingProcessingLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        int todayPendingProcessingCount = iGpOrderService.getCount(todayPendingProcessingLqw);
        j.put("todayPendingProcessingCount", todayPendingProcessingCount);
        // 今日待处理（待拿货）
        QueryWrapper<GpOrder> todayPendingProcessingToBePickingUpGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayPendingProcessingToBePickingUpGoodsLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        todayPendingProcessingToBePickingUpGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_PICKING_UP_GOODS.getKey());
        int todayPendingProcessingToBePickingUpGoodsCount = iGpOrderService.getCount(todayPendingProcessingToBePickingUpGoodsLqw);
        j.put("todayPendingProcessingToBePickingUpGoodsCount", todayPendingProcessingToBePickingUpGoodsCount);
        // 今日待处理（待备货）
        QueryWrapper<GpOrder> todayPendingProcessingToBeStockUpLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayPendingProcessingToBeStockUpLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        todayPendingProcessingToBeStockUpLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_STOCK_UP.getKey());
        int todayPendingProcessingToBeStockUpCount = iGpOrderService.getCount(todayPendingProcessingToBeStockUpLqw);
        j.put("todayPendingProcessingToBeStockUpCount", todayPendingProcessingToBeStockUpCount);
        // 今日待处理（待发货）
        QueryWrapper<GpOrder> todayPendingProcessingToBeSendOutGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayPendingProcessingToBeSendOutGoodsLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        todayPendingProcessingToBeSendOutGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey());
        int todayPendingProcessingToBeSendOutGoodsCount = iGpOrderService.getCount(todayPendingProcessingToBeSendOutGoodsLqw);
        j.put("todayPendingProcessingToBeSendOutGoodsCount", todayPendingProcessingToBeSendOutGoodsCount);
        // 今日待处理（待中转）
        QueryWrapper<GpOrder> todayPendingProcessingToBeTransferLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayPendingProcessingToBeTransferLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        todayPendingProcessingToBeTransferLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_TRANSFER.getKey());
        int todayPendingProcessingToBeTransferCount = iGpOrderService.getCount(todayPendingProcessingToBeTransferLqw);
        j.put("todayPendingProcessingToBeTransferCount", todayPendingProcessingToBeTransferCount);
        // 历史待处理
        QueryWrapper<GpOrder> oldPendingProcessingLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldPendingProcessingLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        int oldPendingProcessingCount = iGpOrderService.getCount(oldPendingProcessingLqw);
        j.put("oldPendingProcessingCount", oldPendingProcessingCount);
        // 历史待处理（待拿货）
        QueryWrapper<GpOrder> oldPendingProcessingToBePickingUpGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldPendingProcessingToBePickingUpGoodsLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        oldPendingProcessingToBePickingUpGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_PICKING_UP_GOODS.getKey());
        int oldPendingProcessingToBePickingUpGoodsCount = iGpOrderService.getCount(oldPendingProcessingToBePickingUpGoodsLqw);
        j.put("oldPendingProcessingToBePickingUpGoodsCount", oldPendingProcessingToBePickingUpGoodsCount);
        // 历史待处理（待备货）
        QueryWrapper<GpOrder> oldPendingProcessingToBeStockUpLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldPendingProcessingToBeStockUpLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        oldPendingProcessingToBeStockUpLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_STOCK_UP.getKey());
        int oldPendingProcessingToBeStockUpCount = iGpOrderService.getCount(oldPendingProcessingToBeStockUpLqw);
        j.put("oldPendingProcessingToBeStockUpCount", oldPendingProcessingToBeStockUpCount);
        // 历史待处理（待发货）
        QueryWrapper<GpOrder> oldPendingProcessingToBeSendOutGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldPendingProcessingToBeSendOutGoodsLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        oldPendingProcessingToBeSendOutGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey());
        int oldPendingProcessingToBeSendOutGoodsCount = iGpOrderService.getCount(oldPendingProcessingToBeSendOutGoodsLqw);
        j.put("oldPendingProcessingToBeSendOutGoodsCount", oldPendingProcessingToBeSendOutGoodsCount);
        // 历史待处理（待中转）
        QueryWrapper<GpOrder> oldPendingProcessingToBeTransferLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldPendingProcessingToBeTransferLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
        oldPendingProcessingToBeTransferLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_TRANSFER.getKey());
        int oldPendingProcessingToBeTransferCount = iGpOrderService.getCount(oldPendingProcessingToBeTransferLqw);
        j.put("oldPendingProcessingToBeTransferCount", oldPendingProcessingToBeTransferCount);
        // 历史中转待处理
        QueryWrapper<GpOrder> oldTransferPendingProcessingLqw = getTransferGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        int oldTransferPendingProcessingCount = 0;
        if (oldTransferPendingProcessingLqw != null) {
            oldTransferPendingProcessingLqw.eq("gp.is_exception", YesNoEnum.NO.getKey());
            oldTransferPendingProcessingCount = iGpOrderService.getCount(oldTransferPendingProcessingLqw);
        }
        j.put("oldTransferPendingProcessingCount", oldTransferPendingProcessingCount);
        // 待处理总数
        j.put("totalPendingProcessingCount", todayPendingProcessingCount + oldPendingProcessingCount + oldTransferPendingProcessingCount);

        // 今日异常
        QueryWrapper<GpOrder> todayExceptionLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayExceptionLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        int todayExceptionCount = iGpOrderService.getCount(todayExceptionLqw);
        j.put("todayExceptionCount", todayExceptionCount);
        // 今日异常（待拿货）
        QueryWrapper<GpOrder> todayExceptionToBePickingUpGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayExceptionToBePickingUpGoodsLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        todayExceptionToBePickingUpGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_PICKING_UP_GOODS.getKey());
        int todayExceptionToBePickingUpGoodsCount = iGpOrderService.getCount(todayExceptionToBePickingUpGoodsLqw);
        j.put("todayExceptionToBePickingUpGoodsCount", todayExceptionToBePickingUpGoodsCount);
        // 今日异常（待备货）
        QueryWrapper<GpOrder> todayExceptionToBeStockUpLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayExceptionToBeStockUpLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        todayExceptionToBeStockUpLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_STOCK_UP.getKey());
        int todayExceptionToBeStockUpCount = iGpOrderService.getCount(todayExceptionToBeStockUpLqw);
        j.put("todayExceptionToBeStockUpCount", todayExceptionToBeStockUpCount);
        // 今日异常（待发货）
        QueryWrapper<GpOrder> todayExceptionToBeSendOutGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayExceptionToBeSendOutGoodsLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        todayExceptionToBeSendOutGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey());
        int todayExceptionToBeSendOutGoodsCount = iGpOrderService.getCount(todayExceptionToBeSendOutGoodsLqw);
        j.put("todayExceptionToBeSendOutGoodsCount", todayExceptionToBeSendOutGoodsCount);
        // 今日异常（待中转）
        QueryWrapper<GpOrder> todayExceptionToBeTransferLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "1");
        todayExceptionToBeTransferLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        todayExceptionToBeTransferLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_TRANSFER.getKey());
        int todayExceptionToBeTransferCount = iGpOrderService.getCount(todayExceptionToBeTransferLqw);
        j.put("todayExceptionToBeTransferCount", todayExceptionToBeTransferCount);
        // 历史异常
        QueryWrapper<GpOrder> oldExceptionLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldExceptionLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        int oldExceptionCount = iGpOrderService.getCount(oldExceptionLqw);
        j.put("oldExceptionCount", oldExceptionCount);
        // 历史异常（待拿货）
        QueryWrapper<GpOrder> oldExceptionToBePickingUpGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldExceptionToBePickingUpGoodsLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        oldExceptionToBePickingUpGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_PICKING_UP_GOODS.getKey());
        int oldExceptionToBePickingUpGoodsCount = iGpOrderService.getCount(oldExceptionToBePickingUpGoodsLqw);
        j.put("oldExceptionToBePickingUpGoodsCount", oldExceptionToBePickingUpGoodsCount);
        // 历史异常（待备货）
        QueryWrapper<GpOrder> oldExceptionToBeStockUpLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldExceptionToBeStockUpLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        oldExceptionToBeStockUpLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_STOCK_UP.getKey());
        int oldExceptionToBeStockUpCount = iGpOrderService.getCount(oldExceptionToBeStockUpLqw);
        j.put("oldExceptionToBeStockUpCount", oldExceptionToBeStockUpCount);
        // 历史异常（待发货）
        QueryWrapper<GpOrder> oldExceptionToBeSendOutGoodsLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldExceptionToBeSendOutGoodsLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        oldExceptionToBeSendOutGoodsLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey());
        int oldExceptionToBeSendOutGoodsCount = iGpOrderService.getCount(oldExceptionToBeSendOutGoodsLqw);
        j.put("oldExceptionToBeSendOutGoodsCount", oldExceptionToBeSendOutGoodsCount);
        // 历史异常（待中转）
        QueryWrapper<GpOrder> oldExceptionToBeTransferLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        oldExceptionToBeTransferLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
        oldExceptionToBeTransferLqw.eq("gp.order_status", OrderStatusEnum.TO_BE_TRANSFER.getKey());
        int oldExceptionToBeTransferCount = iGpOrderService.getCount(oldExceptionToBeTransferLqw);
        j.put("oldExceptionToBeTransferCount", oldExceptionToBeTransferCount);
        j.put("totalExceptionCount", todayExceptionCount + oldExceptionCount);
        // 历史异常中转待处理
        QueryWrapper<GpOrder> oldTransferExceptionLqw = getTransferGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "2");
        int oldTransferExceptionCount = 0;
        if (oldTransferExceptionLqw != null) {
            oldTransferExceptionLqw.eq("gp.is_exception", YesNoEnum.YES.getKey());
            oldTransferExceptionCount = iGpOrderService.getCount(oldTransferExceptionLqw);
        }
        j.put("oldTransferExceptionCount", oldTransferExceptionCount);
        // 异常总数
        j.put("totalExceptionCount", todayExceptionCount + oldExceptionCount + oldTransferExceptionCount);

        gpOrderReq.setOrderStatus(OrderStatusEnum.COMPLETE.getKey());
        QueryWrapper<GpOrder> completeLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "");
        completeLqw.eq("gp.order_status", OrderStatusEnum.COMPLETE.getKey());
        int completeCount = iGpOrderService.getCount(completeLqw);
        j.put("completeCount", completeCount);

        gpOrderReq.setOrderStatus(OrderStatusEnum.COMPLETE.getKey());
        QueryWrapper<GpOrder> forwardLqw = getGpOrderQueryWrapper(gpOrderReq, userId, confirmFlag, sysRoles, "");
        forwardLqw.eq("gp.order_status", OrderStatusEnum.COMPLETE.getKey());
        // 分享页只显示有上传物流单的单子
        forwardLqw.eq("gof.status", YesNoEnum.YES.getKey());
        forwardLqw.in("gof.config_id", 3,4);
        int forwardCount = iGpOrderService.getCount(forwardLqw);
        j.put("forwardCount", forwardCount);

        return AjaxResult.success(j);
    }

    private QueryWrapper<GpOrder> getGpOrderQueryWrapper(GpOrderReq gpOrderReq, Long userId, boolean confirmFlag, List<SysRole> sysRoles, String searchDateType) {
        QueryWrapper<GpOrder> lqw = new QueryWrapper<GpOrder>();
        gpOrderReq.generatorQuery(lqw,true);
        if (confirmFlag) {
            List<Long> orderStatus = gpFlowConfigService.getOrderStatusByUserId(userId);
            lqw.in("gp.order_status", orderStatus);
        } else {
            SysUser sysUser = sysUserMapper.selectUserById(userId);
            SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            if (!StringUtils.equals(gpOrderReq.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
                lqw.ne("gp.order_status" ,OrderStatusEnum.COMPLETE.getKey());
            }
            lqw.eq("gp.organise_unit", sysDept.getDeptName());
            // 如果是销售员(所有角色数据权限都是‘仅本人数据权限’)，查询销售员对应的订单
            List<SysRole> collect = sysRoles.stream().filter(role -> StringUtils.equals(role.getDataScope(), "5")).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect) && collect.size() == sysRoles.size()) {
                lqw.eq("gp.salesman", sysUser.getNickName());
            }
        }
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            if (StringUtils.equals(searchDateType, "2")) {
                lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') < '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
            } else {
                lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
            }
        }
        lqw.eq("gp.is_cancel", YesNoEnum.NO.getKey());
        lqw.groupBy("gp.id");
        return lqw;
    }

    private QueryWrapper<GpOrder> getTransferGpOrderQueryWrapper(GpOrderReq gpOrderReq, Long userId, boolean confirmFlag, List<SysRole> sysRoles, String searchDateType) {
        QueryWrapper<GpOrder> lqw = new QueryWrapper<GpOrder>();
        gpOrderReq.generatorQuery(lqw,true);
        if (confirmFlag) {
            List<Long> orderStatus = gpFlowConfigService.getOrderStatusByUserId(userId);
            if (orderStatus.contains(30L)) {
                // 有中转权限才显示‘中转未处理’
                lqw.eq("gp.order_status", OrderStatusEnum.IN_TRANSIT_DELIVERY.getKey());
            } else {
                return null;
            }
        } else {
            SysUser sysUser = sysUserMapper.selectUserById(userId);
            SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            if (!StringUtils.equals(gpOrderReq.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
                lqw.ne("gp.order_status" ,OrderStatusEnum.COMPLETE.getKey());
            }
            lqw.eq("gp.organise_unit", sysDept.getDeptName());
            // 如果是销售员(所有角色数据权限都是‘仅本人数据权限’)，查询销售员对应的订单
            List<SysRole> collect = sysRoles.stream().filter(role -> StringUtils.equals(role.getDataScope(), "5")).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect) && collect.size() == sysRoles.size()) {
                lqw.eq("gp.salesman", sysUser.getNickName());
            }
        }
        lqw.eq("gp.is_cancel", YesNoEnum.NO.getKey());
        lqw.groupBy("gp.id");
        return lqw;
    }

    /**
     * @Description 查询QC订单数量
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return TableDataInfo
     */
    @ApiOperation("查询QC订单数量")
    @GetMapping("/order/order/getQCCount")
    public AjaxResult getQCCount(GpOrderReq gpOrderReq)
    {
        Map<String, Object> j = new HashMap<>();
        /*Long userId = gpOrderReq.getUserId();
        // 不查询暂停的订单
//        gpOrderReq.setIsSuspend(0);
        if (userId == null) {
            return AjaxResult.error("用户未登录");
        }
        boolean confirmFlag = false;
        // 获取用户角色权限标识
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
        List<String> roleKeyList = sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        // 获取可进行QC流程流转操作的角色权限标识
        // TODO: 待配置QC流程流转角色
        List<String> confirmRoleKeyList = RoleKeyEnum.confirmQCRoleKey();
        // 判断当前用户是否有可操作权限
        if (!CollectionUtils.isEmpty(roleKeyList) && !CollectionUtils.isEmpty(confirmRoleKeyList)) {
            roleKeyList.retainAll(confirmRoleKeyList);
            if (!CollectionUtils.isEmpty(roleKeyList)) {
                confirmFlag = true;
            }
        }*/

        // 生产缺货待办
        QueryWrapper<GpProductionApplication> manufactureApplicationLqw = new QueryWrapper<>();
        manufactureApplicationLqw.eq("type", "1");
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            manufactureApplicationLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            manufactureApplicationLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int manufactureApplicationCount = gpProductionApplicationService.count(manufactureApplicationLqw);
        j.put("manufactureApplicationCount", manufactureApplicationCount);
        // 加工缺货待办
        QueryWrapper<GpProductionApplication> processApplicationLqw = new QueryWrapper<>();
        processApplicationLqw.eq("type", "2");
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            processApplicationLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            processApplicationLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int processApplicationCount = gpProductionApplicationService.count(processApplicationLqw);
        j.put("processApplicationCount", processApplicationCount);
        // 采购缺货待办
        QueryWrapper<GpProductionApplication> purchaseApplicationLqw = new QueryWrapper<>();
        purchaseApplicationLqw.eq("type", "3");
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseApplicationLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseApplicationLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int purchaseApplicationCount = gpProductionApplicationService.count(purchaseApplicationLqw);
        j.put("purchaseApplicationCount", purchaseApplicationCount);
        j.put("totalApplicationCount", manufactureApplicationCount + processApplicationCount + purchaseApplicationCount);

        // 生产做货明细
        QueryWrapper<GpProductionDetails> manufactureDetailsLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            manufactureDetailsLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            manufactureDetailsLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int manufactureDetailsCount = gpProductionDetailsService.count(manufactureDetailsLqw);
        j.put("manufactureDetailsCount", manufactureDetailsCount);

        // 采购做货明细
        QueryWrapper<GpPurchasingMakingDetails> purchaseDetailsLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseDetailsLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseDetailsLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int purchaseDetailsCount = iGpPurchasingMakingDetailsService.count(purchaseDetailsLqw);
        j.put("purchaseDetailsCount", purchaseDetailsCount);
        j.put("totalDetailsCount", manufactureDetailsCount + purchaseDetailsCount);

        // 生产排单待办
        QueryWrapper<GpProductionScheduling> manufactureSchedulingLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            manufactureSchedulingLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            manufactureSchedulingLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int manufactureSchedulingCount = gpProductionSchedulingService.count(manufactureSchedulingLqw);
        j.put("manufactureSchedulingCount", manufactureSchedulingCount);

        // 加工排单待办
        QueryWrapper<GpProcessScheduling> gpProcessSchedulingQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessSchedulingQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessSchedulingQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int processSchedulingCount = gpProcessSchedulingService.count(gpProcessSchedulingQueryWrapper);
        j.put("processSchedulingCount", processSchedulingCount);

        // 采购排单待办
        QueryWrapper<GpProcureScheduling> purchaseSchedulingLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseSchedulingLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseSchedulingLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int purchaseSchedulingCount = iGpProcureSchedulingService.count(purchaseSchedulingLqw);
        j.put("purchaseSchedulingCount", purchaseSchedulingCount);
        j.put("totalSchedulingCount", manufactureSchedulingCount + processSchedulingCount + purchaseSchedulingCount);



        // 生产到货待办
        QueryWrapper<GpDeliveryNote> manufactureDeliveryNoteLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            manufactureDeliveryNoteLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            manufactureDeliveryNoteLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int manufactureDeliveryNoteCount = gpDeliveryNoteService.count(manufactureDeliveryNoteLqw);
        j.put("manufactureDeliveryNoteCount", manufactureDeliveryNoteCount);


        // 加工到货待办
        QueryWrapper<GpProcessDeliveryNote> gpProcessDeliveryNoteQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessDeliveryNoteQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessDeliveryNoteQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int processDeliveryNotecount = gpProcessDeliveryNoteService.count(gpProcessDeliveryNoteQueryWrapper);
        j.put("processDeliveryNotecount", processDeliveryNotecount);

        // 采购到货待办
        QueryWrapper<GpPurchaseReceipt> purchaseDeliveryNoteLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseDeliveryNoteLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseDeliveryNoteLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int purchaseDeliveryNoteCount = iGpPurchaseReceiptService.count(purchaseDeliveryNoteLqw);
        j.put("purchaseDeliveryNoteCount", purchaseDeliveryNoteCount);
        j.put("totalDeliveryNoteCount", manufactureDeliveryNoteCount + processDeliveryNotecount + purchaseDeliveryNoteCount);


        // 生产来料待办
        QueryWrapper<GpIncomingInspect> manufactureIncomingInspectLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            manufactureIncomingInspectLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            manufactureIncomingInspectLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int manufactureIncomingInspectCount = gpIncomingInspectService.count(manufactureIncomingInspectLqw);
        j.put("manufactureIncomingInspectCount", manufactureIncomingInspectCount);



        // 加工来料待办
        QueryWrapper<GpProcessIncomingInspect> gpProcessIncomingInspectQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessIncomingInspectQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessIncomingInspectQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int gpProcessIncomingInspectcount = gpProcessIncomingInspectService.count(gpProcessIncomingInspectQueryWrapper);
        j.put("gpProcessIncomingInspectcount", gpProcessIncomingInspectcount);


        // 采购来料待办
        QueryWrapper<GpPurchaseIncomingInspect> purchaseIncomingInspectLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseIncomingInspectLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseIncomingInspectLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int purchaseIncomingInspectCount = iGpPurchaseIncomingInspectService.count(purchaseIncomingInspectLqw);
        j.put("purchaseIncomingInspectCount", purchaseIncomingInspectCount);
        j.put("totalIncomingInspectCount", manufactureIncomingInspectCount + gpProcessIncomingInspectcount + purchaseIncomingInspectCount);

        //生产追踪
        QueryWrapper<GpProductionFlow> gpProductionFlowQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProductionFlowQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProductionFlowQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int gpProductionFlowcount = gpProductionFlowService.count(gpProductionFlowQueryWrapper);
        j.put("gpProductionFlowcount", gpProductionFlowcount);

        //加工追踪
        QueryWrapper<GpProcessProblemTrack> gpProcessProblemTrackQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessProblemTrackQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessProblemTrackQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int gpProcessProblemTrackcount = gpProcessProblemTrackService.count(gpProcessProblemTrackQueryWrapper);
        j.put("gpProcessProblemTraccount", gpProcessProblemTrackcount);

        // 采购追踪
        QueryWrapper<GpPurchaseTrack> purchaseTrackQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseTrackQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseTrackQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int purchaseTrackCount = iGpPurchaseTrackService.count(purchaseTrackQueryWrapper);
        j.put("purchaseTrackCount", purchaseTrackCount);
        j.put("totalProblemTrackCount", gpProductionFlowcount + gpProcessProblemTrackcount + purchaseTrackCount);


        return AjaxResult.success(j);
    }


    /**
     * @Description 查询QC订单数量
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return TableDataInfo
     */
    @ApiOperation("查询QC订单数量")
    @GetMapping("/order/order/getIncomingInspectCount")
    public AjaxResult getIncomingInspectCount(GpOrderReq gpOrderReq)
    {
        Map<String, Object> j = new HashMap<>();
        // 生产品质反馈
        QueryWrapper<GpQualityfeedback> qualityfeedbackLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            qualityfeedbackLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            qualityfeedbackLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int qualityfeedbackCount = gpQualityfeedbackService.count(qualityfeedbackLqw);
        j.put("qualityfeedbackCount", qualityfeedbackCount);

        // 采购品质反馈
        QueryWrapper<GpPurchaseQualityFeedback> purchaseQualityfeedbackLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseQualityfeedbackLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseQualityfeedbackLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int purchaseQualityfeedbackCount = iGpPurchaseQualityFeedbackService.count(purchaseQualityfeedbackLqw);
        j.put("purchaseQualityfeedbackCount", purchaseQualityfeedbackCount);
        j.put("totalQualityfeedbackCount", qualityfeedbackCount + purchaseQualityfeedbackCount);

        // 生产品质问题跟踪
        QueryWrapper<GpQualityFlowDetails> qualityFlowDetailsLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            qualityFlowDetailsLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            qualityFlowDetailsLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int qualityFeedbackQuestionCount = gpQualityFlowDetailsService.count(qualityFlowDetailsLqw);
        j.put("qualityFeedbackQuestionCount", qualityFeedbackQuestionCount);
        // 采购品质问题跟踪
        QueryWrapper<GpPurchaseQualityFlowDetails> purchaseQualityFlowDetailsLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseQualityFlowDetailsLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseQualityFlowDetailsLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int purchaseQualityFeedbackQuestionCount = iGpPurchaseQualityFlowDetailsService.count(purchaseQualityFlowDetailsLqw);
        j.put("purchaseQualityFeedbackQuestionCount", purchaseQualityFeedbackQuestionCount);
        j.put("totalQualityFeedbackQuestionCount", qualityFeedbackQuestionCount + purchaseQualityFeedbackQuestionCount);

        // 生产克重
        QueryWrapper<GpGramWeight> gramWeightLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gramWeightLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gramWeightLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int gramWeightCount = gpGramWeightService.count(gramWeightLqw);
        j.put("gramWeightCount", gramWeightCount);

        // 采购克重
        QueryWrapper<GpPurchaseGramWeight> purchaseGramWeightLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            purchaseGramWeightLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            purchaseGramWeightLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int purchaseGramWeightCount = iGpPurchaseGramWeightService.count(purchaseGramWeightLqw);
        j.put("purchaseGramWeightCount", purchaseGramWeightCount);
        j.put("totalGramWeightCount", gramWeightCount + purchaseGramWeightCount);

        // 色牢度
        QueryWrapper<GpColorFastness> colorFastnessLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            colorFastnessLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            colorFastnessLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int colorFastnessCount = gpColorFastnessService.count(colorFastnessLqw);
        j.put("colorFastnessCount", colorFastnessCount);

        // 生产甲醛
        QueryWrapper<GpFormaldehydeContrast> formaldehydeContrastLqw = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            formaldehydeContrastLqw.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            formaldehydeContrastLqw.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("colour", gpOrderReq.getSearchName()));
        }
        int formaldehydeContrastCount = gpFormaldehydeContrastService.count(formaldehydeContrastLqw);
        j.put("formaldehydeContrastCount", formaldehydeContrastCount);

        // 加工甲醛
        QueryWrapper<GpProcessFormaldehydeContrast> processFormaldehydeContrastQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            processFormaldehydeContrastQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            processFormaldehydeContrastQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int processFormaldehydeContrastcount = iGpProcessFormaldehydeContrastService.count(processFormaldehydeContrastQueryWrapper);
        j.put("processformaldehydecontrastcount", processFormaldehydeContrastcount);
        j.put("totalformaldehydecontrastcount", formaldehydeContrastCount + processFormaldehydeContrastcount);

        //送检表
        QueryWrapper<GpRevisionTable> gpRevisionTableQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpRevisionTableQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpRevisionTableQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int revisionyablecount = iGpRevisionTableService.count(gpRevisionTableQueryWrapper);
        j.put("revisionyablecount",revisionyablecount);

        //改标表
        QueryWrapper<GpInspectionTable> gpInspectionTableQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpInspectionTableQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpInspectionTableQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int gpinspectiontablecount = iGpInspectionTableService.count(gpInspectionTableQueryWrapper);
        j.put("inspectiontablecount",gpinspectiontablecount);

        return AjaxResult.success(j);
    }

    @ApiOperation("加工列表查询")
    @GetMapping("/order/order/myProcessList")
    public AjaxResult processList(GpOrderReq gpOrderReq){
        Map<String, Object> j = new HashMap<>();

        // 加工溢码率
        QueryWrapper<GpProcessOverflowRate> gpProcessOverflowRateQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessOverflowRateQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessOverflowRateQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int gpProcessOverflowRateCount = gpProcessOverflowRateService.count(gpProcessOverflowRateQueryWrapper);
        j.put("gpProcessOverflowRateCount", gpProcessOverflowRateCount);


        //加工成本核算
        QueryWrapper<GpProcessCosting> gpProcessCostingQueryWrapper = new QueryWrapper<>();
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            gpProcessCostingQueryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
        }
        if (StringUtils.isNotBlank(gpOrderReq.getSearchName())) {
            gpProcessCostingQueryWrapper.and(wrapper -> wrapper.like("sn", gpOrderReq.getSearchName()).or().like("product_name", gpOrderReq.getSearchName()).or().like("product_color", gpOrderReq.getSearchName()));
        }
        int gpProcessCostingCount = gpProcessCostingService.count(gpProcessCostingQueryWrapper);
        j.put("gpProcessCostingCount", gpProcessCostingCount);

        return AjaxResult.success(j);
    }

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return TableDataInfo
     */
    @ApiOperation("我的订单列表")
    @GetMapping("/order/order/myOrderList")
    public TableDataInfo<GpOrderVo> myOrderList(GpOrderReq gpOrderReq)
    {
        Long userId = gpOrderReq.getUserId();
        if (userId == null) {
            return getError("缺少必要参数[userId]");
        }
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (sysUser == null) {
            return getError("用户不存在");
        }
        QueryWrapper<GpOrder> lqw = new QueryWrapper<GpOrder>();
        // 获取用户角色权限标识
        List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
        boolean isAll = sysRoles.stream().anyMatch(role -> role.getDataScope().equals("1"));
        boolean isDept = sysRoles.stream().anyMatch(role -> role.getDataScope().equals("4"));
        if (!isAll) {
            if (isDept) {
                // 查部门订单
                lqw.and(wrapper -> wrapper.apply("find_in_set('" + sysUser.getDeptId() + "', gof.dept_ids)").or().eq("gp.create_by", sysUser.getNickName()));
            } else {
                // 查个人订单
                lqw.and(wrapper -> wrapper.eq("gof.user_id", userId).or().eq("gp.create_by", sysUser.getNickName()));
            }
        }
        // 查询对应日期的数据
        if (gpOrderReq.getSearchDate() != null) {
            if (StringUtils.equals(gpOrderReq.getSearchDateType(), "1")) {
                lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
            } else {
                lqw.apply("DATE_FORMAT(gp.create_time, '%Y-%m-%d') < '" + DateUtils.dateTime(gpOrderReq.getSearchDate()) + "'");
            }
        }
        /*List<SysDictData> dict = dictTypeService.selectDictDataByType("staff_query_days");
        if (CollectionUtils.isNotEmpty(dict)) {
            Integer queryDays = Integer.valueOf(dict.get(0).getDictValue());
            if (queryDays != null) {
                Date now = new Date();
                Date beforeDay = DateUtils.getBeforeDay(now, queryDays);
                lqw.between("gof.create_time", beforeDay, now);
            }
        }*/
        Integer queryDays = sysRoleMapper.selectQueryDaysByUserId(userId);
        if (queryDays != null && queryDays > 0) {
            Date now = new Date();
            Date beforeDay = DateUtils.getBeforeDay(now, queryDays);
            lqw.between("gof.create_time", beforeDay, now);
        } else {
            // 没有设置查看天数或设置为0则不给查看
            return getDataTable(new ArrayList<>());
        }
        if (StringUtils.isNotBlank(gpOrderReq.getFormCode())) {
            lqw.and(wrapper ->
                wrapper.like("gp.form_code" ,gpOrderReq.getFormCode()).or().like("gp.client_name" ,gpOrderReq.getFormCode())
            );
        }
        if (StringUtils.isNotBlank(gpOrderReq.getProductName())) {
            lqw.and(wrapper -> wrapper.like("gp.form_code", gpOrderReq.getProductName())
                    .or().like("gp.client_name", gpOrderReq.getProductName())
                    .or().like("p.product_name", gpOrderReq.getProductName())
                    .or().like("gp.remark", gpOrderReq.getProductName()));

        }
        /*if (StringUtils.isNotBlank(gpOrderReq.getClientName())) {
            lqw.like("gp.client_name" ,gpOrderReq.getClientName());
        }*/
        lqw.groupBy("gp.id");
        startPage();
        List<GpOrderVo> list = iGpOrderService.listVo(lqw);
        for (GpOrderVo gpOrderVo : list) {
            getOrderTime(gpOrderVo);
            this.getFlowStatus(gpOrderVo);
        }
        return getDataTable(list);
    }

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return TableDataInfo
     */
    @ApiOperation("部门订单列表")
    @GetMapping("/order/order/deptOrderList")
    public AjaxResult deptOrderList(GpOrderReq gpOrderReq)
    {
        startPage();
        Long deptId = gpOrderReq.getDeptIds();
        if (deptId == null) {
            return AjaxResult.error("缺少必要参数[deptId]");
        }
        String startDate = null;
        String endDate = null;
        if (gpOrderReq.getSearchDate() != null) {
            startDate = DateUtils.parseDateToStr("YYYY-MM-dd 00:00:00", gpOrderReq.getSearchDate());
            endDate = DateUtils.parseDateToStr("YYYY-MM-dd 23:59:59", gpOrderReq.getSearchDate());
        }
        return AjaxResult.success(gpOrderFlowService.forms(null, deptId.toString(), gpOrderReq.getType(), null, startDate, endDate));
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("通过订单号获取详情")
    @GetMapping(value = "/order/order/getByOrderCloudNumber/{orderCloudNumber}" )
    public AjaxResult getByOrderCloudNumber(HttpServletRequest request, @PathVariable("orderCloudNumber") String orderCloudNumber) {
        String userId = request.getParameter("userId");
        // 查询类型： 1不限制身份
        String type = request.getParameter("type");
        GpOrder order = iGpOrderService.getOne(new QueryWrapper<GpOrder>().eq("order_cloud_number", orderCloudNumber).eq("del_status", YesNoEnum.NO.getKey()));
        return getOrderDetail(userId, type, order);
    }

    private AjaxResult getOrderDetail(String userId, String type, GpOrder order) {
        if (order == null) {
            return AjaxResult.error("该订单未录入系统，请录入后在进行扫码操作");
        }
        if (order.getIsSuspend() == 1) {
            return AjaxResult.error("该订单已暂停，无法进行操作");
        }
        if (StringUtils.equals(order.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey()) && !StringUtils.equals(type,"1")) {
            GpOrderFlow orderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>().eq("order_id", order.getId()).eq("del_status", YesNoEnum.NO.getKey()).orderByDesc("create_time").last("limit 1"));
            if (orderFlow == null) {
                return AjaxResult.error("该订单已完成发货，无需继续操作");
            } else {
                SysUser sysUser = sysUserMapper.selectUserById(orderFlow.getUserId());
                return AjaxResult.error("【" + sysUser.getNickName() + "】" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", orderFlow.getCreateTime()) + "已完成发货，请确认是否重复拿货或备货等");
            }
        }
        GpOrderVo gpOrderVo = Convert.convert(new TypeReference<GpOrderVo>() {}, order);
        gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
        GpOrderFlow orderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>().eq("order_id", gpOrderVo.getId()).eq("del_status", YesNoEnum.NO.getKey()).orderByDesc("create_time").last("limit 1"));
        if (!StringUtils.equals(type, "1")) {
            GpFlowConfig flowConfig;
            if (orderFlow != null) {
                // 获取下一个流转节点
                flowConfig = gpFlowConfigService.getByOrderStatus(gpOrderVo.getOrderStatus());
                // 如果有订单跟进记录，且没有下一步
                if (flowConfig == null) {
                    return AjaxResult.error("该订单已完成，无需继续操作");
                } else {
                    // 接入时间和到期时间使用下一步时间计算
                    gpOrderVo.setInletTime(orderFlow.getProcessingTime());
                    gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(orderFlow.getInletTime(), flowConfig.getRedDuration().intValue()));
                    // TODO:LEE 散剪和大货流转时间区分先不开启，等前端将配置接上去再开
                    if (StringUtils.equals(gpOrderVo.getOrderCharacteristics(), OrderCharacteristicsEnum.LOOSE_SHEAR.getKey())) {
                        gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(orderFlow.getInletTime(), flowConfig.getRedDuration().intValue()));
                    } else {
                        gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(orderFlow.getInletTime(), flowConfig.getBigRedDuration().intValue()));
                    }
                }
            } else {
                // 没有最近的跟进记录，获取第一个节点
                gpOrderVo.setInletTime(gpOrderVo.getCreateTime());
                flowConfig = gpFlowConfigService.getOne(new QueryWrapper<GpFlowConfig>().eq("del_status", YesNoEnum.NO.getKey()).orderByAsc("sort").last("limit 1"));
                if (flowConfig == null) {
                    return AjaxResult.error("该订单已完成，无需继续操作");
                } else {
                    gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(gpOrderVo.getCreateTime(), flowConfig.getRedDuration().intValue()));
                    // TODO:LEE 散剪和大货流转时间区分先不开启，等前端将配置接上去再开
                    if (StringUtils.equals(gpOrderVo.getOrderCharacteristics(), OrderCharacteristicsEnum.LOOSE_SHEAR.getKey())) {
                        gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(gpOrderVo.getCreateTime(), flowConfig.getRedDuration().intValue()));
                    } else {
                        gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(gpOrderVo.getCreateTime(), flowConfig.getBigRedDuration().intValue()));
                    }
                }
            }
            if (gpOrderVo.getSuspendEndTime() != null) {
                gpOrderVo.setInletTime(gpOrderVo.getSuspendEndTime());
            }
            gpOrderVo.setFlowConfig(flowConfig);
            // 查看下一步的权限（角色）
            List<GpFlowConfigRoleRelaVo> flowConfigRoleRelaList = gpFlowConfigRoleRelaService.listVo(new QueryWrapper<GpFlowConfigRoleRela>().eq("config_id", flowConfig.getId()).eq("del_status", YesNoEnum.NO.getKey()));
            List<Long> configRoleList = flowConfigRoleRelaList.stream().map(GpFlowConfigRoleRelaVo::getRoleId).collect(Collectors.toList());
            // 查看当前用户所有的权限（角色）
            List<Long> roleList = sysUserRoleMapper.getroleIdListByUserId(userId);
            if (CollectionUtils.isEmpty(configRoleList) || CollectionUtils.isEmpty(roleList)) {
                if (orderFlow == null) {
                    return AjaxResult.error("当前用户无法进行【" + flowConfig.getName() + "】操作");
                } else if (StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.TO_BE_INSPECTION.getKey())) {
                    return AjaxResult.error("当前用户无法进行【" + flowConfig.getName() + "】操作");
                } else {
                    SysUser sysUser = sysUserMapper.selectUserById(orderFlow.getUserId());
                    return AjaxResult.error("【" + sysUser.getNickName() + "】" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", orderFlow.getCreateTime()) + "已扫码  请确认是是否重复【" + orderFlow.getConfigName() + "】");
                }
            } else {
                configRoleList.retainAll(roleList);
                if (CollectionUtils.isEmpty(configRoleList)) {
                    if (orderFlow == null) {
                        return AjaxResult.error("当前用户无法进行【" + flowConfig.getName() + "】操作");
                    } else if (StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.TO_BE_INSPECTION.getKey())) {
                        return AjaxResult.error("当前用户无法进行【" + flowConfig.getName() + "】操作");
                    } else {
                        SysUser sysUser = sysUserMapper.selectUserById(orderFlow.getUserId());
                        return AjaxResult.error("【" + sysUser.getNickName() + "】" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", orderFlow.getCreateTime()) + "已扫码  请确认是是否重复【" + orderFlow.getConfigName() + "】");
                    }
                }
            }
        }
        gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        gpOrderVo.setConfirmFlag(1);
        return AjaxResult.success(gpOrderVo);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     * @return
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/order/{id}" )
    public AjaxResult getInfo(HttpServletRequest request, @PathVariable("id" ) Long id) {
        String userId = request.getParameter("userId");
        GpOrderVo gpOrderVo = iGpOrderService.getVoById(id);
        if (gpOrderVo.getIsSuspend() == 1) {
            return AjaxResult.error("该订单已暂停，无法进行操作");
        }
        List<GpOrderFlowVo> orderFlowList = gpOrderFlowService.listVo(new QueryWrapper<GpOrderFlow>().eq("gp.order_id", id).eq("gp.del_status", YesNoEnum.NO.getKey()));
        for (GpOrderFlowVo gpOrderFlowVo : orderFlowList) {
            gpOrderFlowVo.setFlowConfig(gpFlowConfigService.getById(gpOrderFlowVo.getConfigId()));
            // 获取订单去向、车次
            if (StringUtils.isNotBlank(gpOrderFlowVo.getDestinationType())) {
                gpOrderVo.setDestinationType(gpOrderFlowVo.getDestinationType());
            }
            if (StringUtils.isNotBlank(gpOrderFlowVo.getDestinationNo())) {
                gpOrderVo.setDestinationNo(gpOrderFlowVo.getDestinationNo());
            }
            if (StringUtils.isNotBlank(gpOrderFlowVo.getAnnex())) {
                gpOrderFlowVo.setAnnexList(Arrays.asList(gpOrderFlowVo.getAnnex().split(",")));
            }
        }
        gpOrderVo.setOrderFlowList(orderFlowList);
        GpFlowConfig flowConfig;
        Integer confirmFlag = 1;
        if (StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.COMPLETE.getKey())) {
            // 订单已完成，不显示按钮
            confirmFlag = 0;
        }
        flowConfig = gpFlowConfigService.getByOrderStatus(gpOrderVo.getOrderStatus());
        // 如果有订单跟进记录，且没有下一步
        if (flowConfig == null) {
            confirmFlag = 0;
        }
        // 查看下一步的权限（角色）
        if (confirmFlag == 1) {
            List<GpFlowConfigRoleRelaVo> flowConfigRoleRelaList = gpFlowConfigRoleRelaService.listVo(new QueryWrapper<GpFlowConfigRoleRela>().eq("config_id", flowConfig.getId()).eq("del_status", YesNoEnum.NO.getKey()));
            List<Long> configRoleList = flowConfigRoleRelaList.stream().map(GpFlowConfigRoleRelaVo::getRoleId).collect(Collectors.toList());
            // 查看当前用户所有的权限（角色）
            List<Long> roleList = sysUserRoleMapper.getroleIdListByUserId(userId);
            if (CollectionUtils.isEmpty(configRoleList) || CollectionUtils.isEmpty(roleList)) {
                confirmFlag = 0;
            } else {
                configRoleList.retainAll(roleList);
                if (CollectionUtils.isEmpty(configRoleList)) {
                    confirmFlag = 0;
                }
            }
        }
        gpOrderVo.setConfirmFlag(confirmFlag);
        getOrderTime(gpOrderVo);
        gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        return AjaxResult.success(gpOrderVo);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/order")
    public AjaxResult add(@Valid @RequestBody GpOrderAdd gpOrderAdd) {
        GpOrder gpOrder = Convert.convert(new TypeReference<GpOrder>() {}, gpOrderAdd);
        return toAjax(iGpOrderService.save(gpOrder) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PostMapping("/order/order/edit")
    public AjaxResult edit(@Valid @RequestBody GpOrderUpdate gpOrderUpdate) {
        GpOrder gpOrder = Convert.convert(new TypeReference<GpOrder>() {}, gpOrderUpdate);
        return toAjax(iGpOrderService.updateById(gpOrder) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/order/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGpOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    private void getOrderTime(GpOrderVo gpOrderVo) {
        gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
        GpOrderFlow orderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>().eq("order_id", gpOrderVo.getId()).eq("del_status", YesNoEnum.NO.getKey()).orderByDesc("create_time").last("limit 1"));
        int redDuration = 0;
        if (orderFlow != null) {
            GpFlowConfig beforeFlowConfig = gpFlowConfigService.getById(orderFlow.getConfigId());
            GpFlowConfig flowConfig = gpFlowConfigService.getByOrderStatus(gpOrderVo.getOrderStatus());
            // 如果有订单跟进记录，且没有下一步
            if (flowConfig == null) {
                // 接入时间和到期时间使用最后一条跟进记录
                gpOrderVo.setInletTime(orderFlow.getInletTime());
                // TODO:LEE 散剪和大货流转时间区分先不开启，等前端将配置接上去再开
//                redDuration = beforeFlowConfig.getRedDuration().intValue();
                if (StringUtils.equals(gpOrderVo.getOrderCharacteristics(), OrderCharacteristicsEnum.LOOSE_SHEAR.getKey())) {
                    redDuration = beforeFlowConfig.getRedDuration().intValue();
                } else {
                    redDuration = beforeFlowConfig.getBigRedDuration().intValue();
                }
                gpOrderVo.setProcessingTime(orderFlow.getProcessingTime());
                gpOrderVo.setFlowConfig(beforeFlowConfig);
            } else {
                // 接入时间和到期时间使用下一步时间计算
                if (gpOrderVo.getSuspendDuration() != null) {
                    gpOrderVo.setInletTime(DateUtils.getAfterMinute(orderFlow.getProcessingTime(), gpOrderVo.getSuspendDuration().intValue()));
                } else {
                    gpOrderVo.setInletTime(orderFlow.getProcessingTime());
                }
                // TODO:LEE 散剪和大货流转时间区分先不开启，等前端将配置接上去再开
//                redDuration = flowConfig.getRedDuration().intValue();
                if (StringUtils.equals(gpOrderVo.getOrderCharacteristics(), OrderCharacteristicsEnum.LOOSE_SHEAR.getKey())) {
                    redDuration = flowConfig.getRedDuration().intValue();
                } else {
                    redDuration = flowConfig.getBigRedDuration().intValue();
                }
                gpOrderVo.setFlowConfig(flowConfig);
            }
        } else {
            if (gpOrderVo.getSuspendDuration() != null) {
                gpOrderVo.setInletTime(DateUtils.getAfterMinute(gpOrderVo.getCreateTime(), gpOrderVo.getSuspendDuration().intValue()));
            } else {
                gpOrderVo.setInletTime(gpOrderVo.getCreateTime());
            }
            GpFlowConfig flowConfig = gpFlowConfigService.getOne(new QueryWrapper<GpFlowConfig>().eq("del_status", YesNoEnum.NO.getKey()).orderByAsc("sort").last("limit 1"));
            if (flowConfig != null) {
                // TODO:LEE 散剪和大货流转时间区分先不开启，等前端将配置接上去再开
//                redDuration = flowConfig.getRedDuration().intValue();
                if (StringUtils.equals(gpOrderVo.getOrderCharacteristics(), OrderCharacteristicsEnum.LOOSE_SHEAR.getKey())) {
                    redDuration = flowConfig.getRedDuration().intValue();
                } else {
                    redDuration = flowConfig.getBigRedDuration().intValue();
                }
                gpOrderVo.setFlowConfig(flowConfig);
            }
        }
        if (gpOrderVo.getSuspendEndTime() != null) {
            gpOrderVo.setInletTime(gpOrderVo.getSuspendEndTime());
        }
        if (redDuration > 0) {
            gpOrderVo.setExpirationTime(DateUtils.getAfterMinute(gpOrderVo.getInletTime(), redDuration));
            if (StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.TO_BE_PICKING_UP_GOODS.getKey()) || StringUtils.equals(gpOrderVo.getOrderStatus(), OrderStatusEnum.TO_BE_STOCK_UP.getKey())) {
                // 如果是拿货、备货，判断是否在休息时间内，在休息时间内的话需要延长预计结束时间
                LocalTime noonStartTime = LocalTime.of(12, 30, 0); // 中午休息开始时间：12:30:00
                LocalTime noonEndTime = LocalTime.of(13, 0, 0); // 中午休息结束时间：13:00:00
                LocalTime nightStartTime = LocalTime.of(18, 30, 0); // 晚上休息开始时间：18:30:00
                LocalTime nightEndTime = LocalTime.of(19, 0, 0); // 晚上休息结束时间：19:00:00
                // 流入时间
                Instant inletInstant = gpOrderVo.getInletTime().toInstant();
                LocalTime inletTime = inletInstant.atZone(ZoneId.systemDefault()).toLocalTime();
                // 预计完成时间
                Instant expirationInstant = gpOrderVo.getExpirationTime().toInstant();
                LocalTime expirationTime = expirationInstant.atZone(ZoneId.systemDefault()).toLocalTime();
                // 计算预计完成时间
                // 如果流入时间<12:30<预计完成时间<13:00或流入时间<12:30<13:00<预计完成时间，预计完成时间为：流入时间+操作超时时长+休息时长
                long caseOneNoonTime = extendTimeCaseOne(inletTime, expirationTime, noonStartTime, noonEndTime);
                // 如果流入时间<18:30<预计完成时间<19:00或流入时间<18:30<19:00<预计完成时间，预计完成时间为：流入时间+操作超时时长+休息时长
                long caseOneNightTime = extendTimeCaseOne(inletTime, expirationTime, nightStartTime, nightEndTime);
                // 如果12:30<流入时间<13:00，预计完成时间为：休息结束时间-流入时间+操作超时时长
                long caseTwoNoonTime = extendTimeCaseTwo(inletTime, expirationTime, noonStartTime, noonEndTime);
                // 如果18:30<流入时间<19:00，预计完成时间为：休息结束时间-流入时间+操作超时时长
                long caseTwoNightTime = extendTimeCaseTwo(inletTime, expirationTime, nightStartTime, nightEndTime);
                LocalTime caseTime = inletTime.plusMinutes(redDuration).plusMinutes(caseOneNoonTime).plusMinutes(caseOneNightTime).plusMinutes(caseTwoNoonTime).plusMinutes(caseTwoNightTime);
                LocalDate expirationDate = expirationInstant.atZone(ZoneId.systemDefault()).toLocalDate();
                LocalDateTime caseDateTime = LocalDateTime.of(expirationDate, caseTime);
                Date date = java.sql.Timestamp.valueOf(caseDateTime);
                gpOrderVo.setExpirationTime(date);
            }
        }
        // 计算订单时长
        if (gpOrderVo.getOrderDuration() == null) {
            // 获取订单所有流程的总时长
            Long orderDuration = gpOrderFlowService.getTotalDuration(gpOrderVo.getId());
            orderDuration += DateUtils.getDateMinDiff(new Date(), gpOrderVo.getInletTime());
            gpOrderVo.setOrderDuration(orderDuration);
        }
    }

    /**
     * 如果(流入时间<休息开始时间<预计完成时间<休息结束时间)或(流入时间<休息开始时间<休息结束时间<预计完成时间)，预计完成时间为：操作超时时长+休息时长
     * @param inletTime 流入时间
     * @param expirationTime 预计完成时间
     * @param startTime 休息开始时间
     * @param endTime 休息结束时间
     * @return
     */
    private long extendTimeCaseOne(LocalTime inletTime, LocalTime expirationTime, LocalTime startTime, LocalTime endTime) {
        // 获取当前时间
        LocalTime nowTime = LocalTime.now();
        if (inletTime.compareTo(startTime) < 0 &&  //流入时间<休息开始时间
                (expirationTime.compareTo(startTime) > 0 || nowTime.compareTo(startTime) > 0)) {  //休息开始时间<预计完成时间/当前时间
            // 休息时长
            return Duration.between(startTime, endTime).toMinutes();
        }
        return 0;
    }

    /**
     * 如果(休息开始时间<流入时间<休息结束时间)，预计完成时间为：休息结束时间-流入时间+操作超时时长
     * @param inletTime 流入时间
     * @param expirationTime 预计完成时间
     * @param startTime 休息开始时间
     * @param endTime 休息结束时间
     * @return
     */
    private long extendTimeCaseTwo(LocalTime inletTime, LocalTime expirationTime, LocalTime startTime, LocalTime endTime) {
        if (inletTime.compareTo(startTime) > 0 && inletTime.compareTo(endTime) < 0) { // 休息开始时间<流入时间<休息结束时间
            // 休息结束时间-流入时间
            return Duration.between(inletTime, endTime).toMinutes();
        }
        return 0;
    }

    /**
     * @Description 订单采集
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return TableDataInfo
     */
    @ApiOperation("订单采集")
    @PostMapping("/order/order/collection")
    public AjaxResult collection(@Valid @RequestBody GpOrderAddMy gpOrderAddMy) throws Exception {
        // 发送HTTP请求获取XML数据
        String orderCloudNumber = gpOrderAddMy.getOrderCloudNumber();
        URL url = new URL("https://bch5.taobubao.com/api/H5PayService/OrderLetter/Entrance?Number=" + orderCloudNumber + "&from=1");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
//            DataVo data = objectMapper.readValue(sb.toString(), DataVo.class);
            Map<String, Object> dataMap = objectMapper.readValue(sb.toString(), Map.class);
            if (dataMap == null) {
                return AjaxResult.error("获取不到订单信息");
            }
            DataVo data = initData(dataMap);

            if (data.getResultCode() != 200) {
                return AjaxResult.error("获取订单状态异常：ResultCode=" + data.getResultCode());
            }
            if (StringUtils.isNotBlank(data.getOrderContent())) {
                Map<String, Object> map = objectMapper.readValue(data.getOrderContent(), Map.class);
                GpOrderAdd orderAdd = this.initOrder(map);
                if (orderAdd == null) {
                    return AjaxResult.error("获取不到订单信息");
                }
                if (gpOrderAddMy.getUserId() != null) {
                    SysUser sysUser = sysUserMapper.selectUserById(gpOrderAddMy.getUserId());
                    if (sysUser != null) {
                        orderAdd.setCreateBy(sysUser.getNickName());
                    }
                }
                return iGpOrderService.collection(orderAdd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("录入失败");
    }

    private DataVo initData(Map<String, Object> dataMap) {
        DataVo dataVo = new DataVo();
        if (dataMap.get("ResultCode") != null) {
            dataVo.setResultCode(Integer.parseInt(dataMap.get("ResultCode").toString()));
        }
        if (dataMap.get("ResultMessage") != null) {
            dataVo.setResultMessage(dataMap.get("ResultMessage").toString());
        }
        if (dataMap.get("BrandName") != null) {
            dataVo.setBrandName(dataMap.get("BrandName").toString());
        }
        if (dataMap.get("H5PayQR64") != null) {
            dataVo.setH5PayQR64(dataMap.get("H5PayQR64").toString());
        }
        if (dataMap.get("InspectDetailEnable") != null) {
            dataVo.setInspectDetailEnable(Boolean.parseBoolean(dataMap.get("InspectDetailEnable").toString()));
        }
        if (dataMap.get("IsESEnable") != null) {
            dataVo.setIsESEnable(Boolean.parseBoolean(dataMap.get("IsESEnable").toString()));
        }
        if (dataMap.get("IsESSigned") != null) {
            dataVo.setIsESSigned(Boolean.parseBoolean(dataMap.get("IsESSigned").toString()));
        }
        if (dataMap.get("IsOfflineAccountEnable") != null) {
            dataVo.setIsOfflineAccountEnable(Boolean.parseBoolean(dataMap.get("IsOfflineAccountEnable").toString()));
        }
        if (dataMap.get("IsPaid") != null) {
            dataVo.setIsPaid(Boolean.parseBoolean(dataMap.get("IsPaid").toString()));
        }
        if (dataMap.get("IsPayEnable") != null) {
            dataVo.setIsPayEnable(Boolean.parseBoolean(dataMap.get("IsPayEnable").toString()));
        }
        if (dataMap.get("OrderContent") != null) {
            dataVo.setOrderContent(dataMap.get("OrderContent").toString());
        }
        if (dataMap.get("OrderID") != null) {
            dataVo.setOrderID(Long.parseLong(dataMap.get("OrderID").toString()));
        }
        if (dataMap.get("OrderNumber") != null) {
            dataVo.setOrderNumber(dataMap.get("OrderNumber").toString());
        }
        if (dataMap.get("OrderType") != null) {
            dataVo.setOrderType(Integer.parseInt(dataMap.get("OrderType").toString()));
        }
        if (dataMap.get("PayDiscount") != null) {
            dataVo.setPayDiscount(dataMap.get("PayDiscount").toString());
        }
        if (dataMap.get("PayingSource") != null) {
            dataVo.setPayingSource(Integer.parseInt(dataMap.get("PayingSource").toString()));
        }
        if (dataMap.get("WechatPayEnable") != null) {
            dataVo.setWechatPayEnable(Boolean.parseBoolean(dataMap.get("WechatPayEnable").toString()));
        }
        return dataVo;
    }

    private GpOrderAdd initOrder(Map<String, Object> map)  throws Exception {
        GpOrderAdd gpOrderAdd = new GpOrderAdd();
        if (map.get("FormName") != null) {
            gpOrderAdd.setFormName(map.get("FormName").toString());
        }
        if (map.get("OrganiseUnit") != null) {
            gpOrderAdd.setOrganiseUnit(map.get("OrganiseUnit").toString());
        }
        if (map.get("FormType") != null) {
            gpOrderAdd.setFormType(Long.parseLong(map.get("FormType").toString()));
        }
        if (map.get("ClientName") != null) {
            gpOrderAdd.setClientName(map.get("ClientName").toString());
        }
        if (map.get("FormCode") != null) {
            gpOrderAdd.setFormCode(map.get("FormCode").toString());
        }
        if (map.get("ExpectPayment") != null) {
            gpOrderAdd.setExpectPayment(map.get("ExpectPayment").toString());
        }
        if (map.get("TotalBranchesQuantity") != null) {
            gpOrderAdd.setTotalBranchesQuantity(map.get("TotalBranchesQuantity").toString());
        }
        if (map.get("TotalQuantity") != null) {
            gpOrderAdd.setTotalQuantity(map.get("TotalQuantity").toString());
        }
        if (map.get("TotalPostQuantity") != null) {
            gpOrderAdd.setTotalPostQuantity(map.get("TotalPostQuantity").toString());
        }
        if (map.get("Freight") != null) {
            gpOrderAdd.setFreight(map.get("Freight").toString());
        }
        if (map.get("Remark") != null) {
            gpOrderAdd.setRemark(map.get("Remark").toString());
        }
        if (map.get("LinkManAndPhone") != null) {
            gpOrderAdd.setLinkManAndPhone(map.get("LinkManAndPhone").toString());
        }
        if (map.get("Address") != null) {
            gpOrderAdd.setAddress(map.get("Address").toString());
        }
        if (map.get("IsValid") != null) {
            gpOrderAdd.setValid(Boolean.parseBoolean(map.get("IsValid").toString()));
        }
        if (map.get("IsShowBatchNO") != null) {
            gpOrderAdd.setShowBatchNo(Boolean.parseBoolean(map.get("IsShowBatchNO").toString()));
        }
        if (map.get("IsShowFreight") != null) {
            gpOrderAdd.setShowFreight(Boolean.parseBoolean(map.get("IsShowFreight").toString()));
        }
        if (map.get("IsShowRemark") != null) {
            gpOrderAdd.setShowRemark(Boolean.parseBoolean(map.get("IsShowRemark").toString()));
        }
        if (map.get("IsShowLinkManAndPhone") != null) {
            gpOrderAdd.setShowLinkManAndPhone(Boolean.parseBoolean(map.get("IsShowLinkManAndPhone").toString()));
        }
        if (map.get("IsShowAddress") != null) {
            gpOrderAdd.setShowAddress(Boolean.parseBoolean(map.get("IsShowAddress").toString()));
        }
        if (map.get("IsShowPostQuantity") != null) {
            gpOrderAdd.setShowPostQuantity(Boolean.parseBoolean(map.get("IsShowPostQuantity").toString()));
        }
        if (map.get("IsShowPrice") != null) {
            gpOrderAdd.setShowPrice(Boolean.parseBoolean(map.get("IsShowPrice").toString()));
        }
        if (map.get("AdjustAmount") != null) {
            gpOrderAdd.setAdjustAmount(map.get("AdjustAmount").toString());
        }
        if (map.get("AdvanceAmount") != null) {
            gpOrderAdd.setAdvanceAmount(map.get("AdvanceAmount").toString());
        }
        if (map.get("CollectingAmount") != null) {
            gpOrderAdd.setCollectingAmount(map.get("CollectingAmount").toString());
        }
        if (map.get("PaidInOrOut") != null) {
            gpOrderAdd.setPaidInOrOut(map.get("PaidInOrOut").toString());
        }
        if (map.get("OrderBalance") != null) {
            gpOrderAdd.setOrderBalance(map.get("OrderBalance").toString());
        }
        if (map.get("OrderCloudNumber") != null) {
            gpOrderAdd.setOrderCloudNumber(map.get("OrderCloudNumber").toString());
        }
        if (map.get("Merchandiser") != null) {
            gpOrderAdd.setSalesman(map.get("Merchandiser").toString());
        }
        Object productList = map.get("ProductList");
        if (productList != null) {
            ObjectMapper mapper = new ObjectMapper();
            List<GpProductUpdate> productAddList = mapper.convertValue(productList, new com.fasterxml.jackson.core.type.TypeReference<List<GpProductUpdate>>(){});
            if (CollectionUtils.isNotEmpty(productAddList)) {
                productAddList.forEach(gpProductUpdate -> gpProductUpdate.setId(null));
                gpOrderAdd.setProductList(productAddList);
            }
        }
        return gpOrderAdd;
    }

    /**
     * @Description 物流单扫码详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("物流单扫码详情")
    @GetMapping(value = "/order/order/getLogisticsOrder/{orderCloudNumber}" )
    public AjaxResult getLogisticsOrder(HttpServletRequest request, @PathVariable("orderCloudNumber") String orderCloudNumber) {
        String userId = request.getParameter("userId");
        // 精准查询一条数据
        GpOrder order = iGpOrderService.getOne(new QueryWrapper<GpOrder>().eq("order_cloud_number", orderCloudNumber).eq("del_status", YesNoEnum.NO.getKey()));
        if (order == null) {
            return AjaxResult.error("该订单未录入系统，请录入后在进行扫码操作");
        }
        GpOrderFlow gpOrderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>()
                .eq("del_status", YesNoEnum.NO.getKey())
                .eq("order_id", order.getId())
                .eq("destination_type", DestinationTypeEnum.LOGISTICS.getKey())
                .orderByDesc("create_time")
                .last("limit 1"));
        if (gpOrderFlow == null) {
            return AjaxResult.error("该订单未物流发货，无法进行物流单上传");
        }
        // 限制只能自己流转的单子或主管可以上传
        /*if (gpOrderFlow.getUserId() == null || !StringUtils.equals(gpOrderFlow.getUserId().toString(), userId)) {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(Long.parseLong(userId));
            if (CollectionUtils.isEmpty(sysRoles) || !sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList()).contains(RoleKeyEnum.DELIVERY_LEADER.getKey())) {
                return AjaxResult.error("该订单物流发货流程不是当前账号操作的，无法进行物流单上传");
            }
        }*/
        GpOrderVo gpOrderVo = Convert.convert(new TypeReference<GpOrderVo>() {}, order);
        gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
        gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        gpOrderVo.setOrderFlowId(gpOrderFlow.getId());
        return AjaxResult.success(gpOrderVo);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("通过订单号获取详情")
    @GetMapping(value = "/order/order/getByFormCode/{formCode}" )
    public AjaxResult getByFormCode(HttpServletRequest request, @PathVariable("formCode") String formCode) {
        String userId = request.getParameter("userId");
        // 模糊查询多条数据
        List<GpOrderVo> gpOrderVoList = iGpOrderService.listVo(new QueryWrapper<GpOrder>()
                .like("gp.form_code", formCode)
                .eq("gp.del_status", YesNoEnum.NO.getKey())
                .eq("gof.destination_type", DestinationTypeEnum.LOGISTICS.getKey())
                .groupBy("gp.id"));
        if (CollectionUtils.isEmpty(gpOrderVoList)) {
            return AjaxResult.error("未找到满足条件的订单");
        }
        for (GpOrderVo gpOrderVo : gpOrderVoList) {
            gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
            gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        }
        return AjaxResult.success(gpOrderVoList);
        /*GpOrder order = iGpOrderService.getOne(new QueryWrapper<GpOrder>().eq("form_code", formCode).eq("del_status", YesNoEnum.NO.getKey()));
        if (order == null) {
            return AjaxResult.error("该订单未录入系统，请录入后在进行扫码操作");
        }
        GpOrderFlow gpOrderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>()
                .eq("del_status", YesNoEnum.NO.getKey())
                .eq("order_id", order.getId())
                .eq("destination_type", DestinationTypeEnum.LOGISTICS.getKey())
                .orderByDesc("create_time")
                .last("limit 1"));
        if (gpOrderFlow == null) {
            return AjaxResult.error("该订单未物流发货，无法进行物流单上传");
        }*/
        // 限制只能自己流转的单子或主管可以上传
        /*if (gpOrderFlow.getUserId() == null || !StringUtils.equals(gpOrderFlow.getUserId().toString(), userId)) {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(Long.parseLong(userId));
            if (CollectionUtils.isEmpty(sysRoles) || !sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList()).contains(RoleKeyEnum.DELIVERY_LEADER.getKey())) {
                return AjaxResult.error("该订单物流发货流程不是当前账号操作的，无法进行物流单上传");
            }
        }*/
        /*GpOrderVo gpOrderVo = Convert.convert(new TypeReference<GpOrderVo>() {}, order);
        gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
        gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        gpOrderVo.setOrderFlowId(gpOrderFlow.getId());
        return AjaxResult.success(gpOrderVo);*/
    }

    /**
     * @Description 自提扫码详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("自提扫码详情")
    @GetMapping(value = "/order/order/getSelfPickupOrder/{orderCloudNumber}" )
    public AjaxResult getSelfPickupOrder(HttpServletRequest request, @PathVariable("orderCloudNumber") String orderCloudNumber) {
        String userId = request.getParameter("userId");
        GpOrder order = iGpOrderService.getOne(new QueryWrapper<GpOrder>().eq("order_cloud_number", orderCloudNumber).eq("del_status", YesNoEnum.NO.getKey()));
        if (order == null) {
            return AjaxResult.error("该订单未录入系统，请录入后在进行扫码操作");
        }
        GpOrderFlow gpOrderFlow = gpOrderFlowService.getOne(new QueryWrapper<GpOrderFlow>()
                .eq("del_status", YesNoEnum.NO.getKey())
                .eq("order_id", order.getId())
                .eq("destination_type", DestinationTypeEnum.SELF_PICKUP.getKey())
                .orderByDesc("create_time")
                .last("limit 1"));
        if (gpOrderFlow == null) {
            return AjaxResult.error("该订单未物流发货，无法进行物流单上传");
        }
        // 限制只能自己流转的单子或主管可以上传
        /*if (gpOrderFlow.getUserId() == null || !StringUtils.equals(gpOrderFlow.getUserId().toString(), userId)) {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(Long.parseLong(userId));
            if (CollectionUtils.isEmpty(sysRoles) || !sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toList()).contains(RoleKeyEnum.DELIVERY_LEADER.getKey())) {
                return AjaxResult.error("该订单物流发货流程不是当前账号操作的，无法进行物流单上传");
            }
        }*/
        GpOrderVo gpOrderVo = Convert.convert(new TypeReference<GpOrderVo>() {}, order);
        gpOrderVo.setProductList(gpProductService.productListByOrderId(gpOrderVo.getId()));
        gpOrderVo.setRemark(gpOrderVo.getRemark() + " " + gpOrderVo.getLinkManAndPhone());
        gpOrderVo.setOrderFlowId(gpOrderFlow.getId());
        return AjaxResult.success(gpOrderVo);
    }

    /**
     * @Description 获取订单细码图片/物流单
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     * @return
     */
    @ApiOperation("获取订单细码图片/物流单")
    @GetMapping(value = "/order/order/getFlowAnnex" )
    public AjaxResult getFlowAnnex(GpOrderReq gpOrderReq) {
        if (gpOrderReq == null || gpOrderReq.getId() == null || StringUtils.isBlank(gpOrderReq.getOrderStatus())) {
            return AjaxResult.error("缺少必要参数");
        }
        List<String> annexList = this.getAnnexList(gpOrderReq.getId(), gpOrderReq.getOrderStatus());
        return AjaxResult.success(annexList);
    }

    private List<String> getAnnexList(Long id, String status) {
        QueryWrapper<GpOrderFlow> lqw = new QueryWrapper<GpOrderFlow>()
                .eq("gp.del_status", YesNoEnum.NO.getKey())
                .eq("gp.order_id", id);
        if (StringUtils.equals(status, "1")) { // 细码
            lqw.eq("fc.sort", OrderStatusEnum.TO_BE_SEND_OUT_GOODS.getKey());
        } else if (StringUtils.equals(status, "2")) { // 物流单
            lqw.eq("gp.destination_type", DestinationTypeEnum.LOGISTICS.getKey());
        } else if (StringUtils.equals(status, "3")) { // 自提
            lqw.eq("gp.destination_type", DestinationTypeEnum.SELF_PICKUP.getKey());
        }
        String annex = gpOrderFlowService.getAnnexList(lqw);
        List<String> annexList = new ArrayList<>();
        if (StringUtils.isNotBlank(annex)) {
            annexList = Arrays.asList(annex.split(","));
        }
        return annexList;
    }

    /** order end **/

    /** destinationNoConfig begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoConfig
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/destinationNoConfig/list")
    public TableDataInfo<GpDestinationNoConfigVo> destinationNoConfigList(GpDestinationNoConfigReq gpDestinationNoConfigReq)
    {
        startPage();
        QueryWrapper<GpDestinationNoConfig> lqw = new QueryWrapper<GpDestinationNoConfig>();
        gpDestinationNoConfigReq.generatorQuery(lqw,true);
        lqw.orderByAsc("gp.sort");
        List<GpDestinationNoConfigVo> list = iGpDestinationNoConfigService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoConfig
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/destinationNoConfig/{id}" )
    public AjaxResult<GpDestinationNoConfigVo> destinationNoConfigGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpDestinationNoConfigService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoConfig
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/destinationNoConfig")
    public AjaxResult destinationNoConfigAdd(@Valid @RequestBody GpDestinationNoConfigAdd gpDestinationNoConfigAdd) {
        GpDestinationNoConfig gpDestinationNoConfig = Convert.convert(new TypeReference<GpDestinationNoConfig>() {}, gpDestinationNoConfigAdd);
        return toAjax(iGpDestinationNoConfigService.save(gpDestinationNoConfig) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoConfig
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/destinationNoConfig")
    public AjaxResult destinationNoConfigEdit(@Valid @RequestBody GpDestinationNoConfigUpdate gpDestinationNoConfigUpdate) {
        GpDestinationNoConfig gpDestinationNoConfig = Convert.convert(new TypeReference<GpDestinationNoConfig>() {}, gpDestinationNoConfigUpdate);
        return toAjax(iGpDestinationNoConfigService.updateById(gpDestinationNoConfig) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoConfig
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/destinationNoConfig/{ids}" )
    public AjaxResult destinationNoConfigRemove(@PathVariable Long[] ids) {
        return toAjax(iGpDestinationNoConfigService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** destinationNoConfig end **/

    /** 车次发车记录 destinationNoLog begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoLog
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/destinationNoLog/list")
    public TableDataInfo<GpDestinationNoLogVo> destinationNoLogList(GpDestinationNoLogReq gpDestinationNoLogReq)
    {
        startPage();
        QueryWrapper<GpDestinationNoLog> lqw = new QueryWrapper<GpDestinationNoLog>();
        gpDestinationNoLogReq.generatorQuery(lqw,true);
        lqw.orderByAsc("gp.status");
        lqw.orderByDesc("gp.create_time");
        List<GpDestinationNoLogVo> list = iGpDestinationNoLogService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoLog
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/destinationNoLog/{id}" )
    public AjaxResult<GpDestinationNoLogVo> destinationNoLogGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpDestinationNoLogService.getVoById(id));
    }

    /**
     * @Description 新增（发车）
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoLog
     * @Return AjaxResult
     */
    @ApiOperation("新增（发车）")
    @PostMapping("/order/destinationNoLog")
    public AjaxResult destinationNoLogAdd(@Valid @RequestBody GpDestinationNoLogAdd gpDestinationNoLogAdd) {
        GpDestinationNoLog one = iGpDestinationNoLogService.getOne(new LambdaQueryWrapper<GpDestinationNoLog>()
                .eq(GpDestinationNoLog::getDelStatus, YesNoEnum.NO.getKey())
                .eq(GpDestinationNoLog::getDestinationNoId, gpDestinationNoLogAdd.getDestinationNoId())
                .last("and date_format(departure_time, '%Y-%m-%d') = '" + DateUtils.dateTime(gpDestinationNoLogAdd.getDepartureTime()) + "' limit 1"));
        if (one != null) {
            return AjaxResult.error("该车次当天已发，请勿重复发车！");
        }
        gpDestinationNoLogAdd.setStatus("1");
        GpDestinationNoLog gpDestinationNoLog = Convert.convert(new TypeReference<GpDestinationNoLog>() {}, gpDestinationNoLogAdd);
        boolean save = iGpDestinationNoLogService.save(gpDestinationNoLog);
        gpDestinationNoLog.setCreateBy(gpDestinationNoLogAdd.getCreateBy());
        iGpDestinationNoLogService.updateById(gpDestinationNoLog);
        return toAjax(save ? 1 : 0);
    }

    /**
     * @Description 修改（到达）
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoLog
     * @Return AjaxResult
     */
    @ApiOperation("修改（到达）")
    @PutMapping("/order/destinationNoLog")
    public AjaxResult destinationNoLogEdit(@Valid @RequestBody GpDestinationNoLogUpdate gpDestinationNoLogUpdate) {
        GpDestinationNoLog gpDestinationNoLog = Convert.convert(new TypeReference<GpDestinationNoLog>() {}, gpDestinationNoLogUpdate);
        gpDestinationNoLog.setArrivalTime(new Date());
        gpDestinationNoLog.setStatus("2");
        return toAjax(iGpDestinationNoLogService.updateById(gpDestinationNoLog) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpDestinationNoLog
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/destinationNoLog/{ids}" )
    public AjaxResult destinationNoLogRemove(@PathVariable Long[] ids) {
        return toAjax(iGpDestinationNoLogService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 车次发车记录 destinationNoLog end **/

    /** 流转节点配置 flowConfig begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfig
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/flowConfig/list")
    public TableDataInfo<GpFlowConfigVo> flowConfigList(GpFlowConfigReq gpFlowConfigReq)
    {
        startPage();
        QueryWrapper<GpFlowConfig> lqw = new QueryWrapper<GpFlowConfig>();
        gpFlowConfigReq.generatorQuery(lqw,true);
        List<GpFlowConfigVo> list = iGpFlowConfigService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfig
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/flowConfig/{id}" )
    public AjaxResult<GpFlowConfigVo> flowConfigGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpFlowConfigService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfig
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/flowConfig")
    public AjaxResult flowConfigAdd(@Valid @RequestBody GpFlowConfigAdd gpFlowConfigAdd) {
        GpFlowConfig gpFlowConfig = Convert.convert(new TypeReference<GpFlowConfig>() {}, gpFlowConfigAdd);
        return toAjax(iGpFlowConfigService.save(gpFlowConfig) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfig
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/flowConfig")
    public AjaxResult flowConfigEdit(@Valid @RequestBody GpFlowConfigUpdate gpFlowConfigUpdate) {
        GpFlowConfig gpFlowConfig = Convert.convert(new TypeReference<GpFlowConfig>() {}, gpFlowConfigUpdate);
        return toAjax(iGpFlowConfigService.updateById(gpFlowConfig) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfig
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/flowConfig/{ids}" )
    public AjaxResult flowConfigRemove(@PathVariable Long[] ids) {
        return toAjax(iGpFlowConfigService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 流转节点配置 flowConfig end **/

    /** 流转节点角色关联 flowConfigRoleRela begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfigRoleRela
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/flowConfigRoleRela/list")
    public TableDataInfo<GpFlowConfigRoleRelaVo> flowConfigRoleRelaList(GpFlowConfigRoleRelaReq gpFlowConfigRoleRelaReq)
    {
        startPage();
        QueryWrapper<GpFlowConfigRoleRela> lqw = new QueryWrapper<GpFlowConfigRoleRela>();
        gpFlowConfigRoleRelaReq.generatorQuery(lqw,true);
        List<GpFlowConfigRoleRelaVo> list = iGpFlowConfigRoleRelaService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfigRoleRela
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/flowConfigRoleRela/{id}" )
    public AjaxResult<GpFlowConfigRoleRelaVo> flowConfigRoleRelaGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpFlowConfigRoleRelaService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfigRoleRela
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/flowConfigRoleRela")
    public AjaxResult flowConfigRoleRelaAdd(@Valid @RequestBody GpFlowConfigRoleRelaAdd gpFlowConfigRoleRelaAdd) {
        GpFlowConfigRoleRela gpFlowConfigRoleRela = Convert.convert(new TypeReference<GpFlowConfigRoleRela>() {}, gpFlowConfigRoleRelaAdd);
        return toAjax(iGpFlowConfigRoleRelaService.save(gpFlowConfigRoleRela) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfigRoleRela
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/flowConfigRoleRela")
    public AjaxResult flowConfigRoleRelaEdit(@Valid @RequestBody GpFlowConfigRoleRelaUpdate gpFlowConfigRoleRelaUpdate) {
        GpFlowConfigRoleRela gpFlowConfigRoleRela = Convert.convert(new TypeReference<GpFlowConfigRoleRela>() {}, gpFlowConfigRoleRelaUpdate);
        return toAjax(iGpFlowConfigRoleRelaService.updateById(gpFlowConfigRoleRela) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpFlowConfigRoleRela
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/flowConfigRoleRela/{ids}" )
    public AjaxResult flowConfigRoleRelaRemove(@PathVariable Long[] ids) {
        return toAjax(iGpFlowConfigRoleRelaService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 流转节点角色关联 flowConfigRoleRela end **/

    /** 转发记录 forwardLog begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLog
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/forwardLog/list")
    public TableDataInfo<GpForwardLogVo> forwardLogList(GpForwardLogReq gpForwardLogReq)
    {
        startPage();
        QueryWrapper<GpForwardLog> lqw = new QueryWrapper<GpForwardLog>();
        gpForwardLogReq.generatorQuery(lqw,true);
        List<GpForwardLogVo> list = iGpForwardLogService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLog
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/forwardLog/{id}" )
    public AjaxResult<GpForwardLogVo> forwardLogGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpForwardLogService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLog
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/forwardLog")
    @Transactional
    public AjaxResult forwardLogAdd(@Valid @RequestBody GpForwardLogAdd gpForwardLogAdd) {
        if (CollectionUtils.isEmpty(gpForwardLogAdd.getForwardLogDetailAddList())) {
            return AjaxResult.error("请至少选择一个订单进行转发");
        }
        GpForwardLog gpForwardLog = Convert.convert(new TypeReference<GpForwardLog>() {}, gpForwardLogAdd);
        boolean save = iGpForwardLogService.save(gpForwardLog);
        if (save) {
            List<GpForwardLogDetail> forwardLogDetailList = new ArrayList<>();
            GpForwardLogDetail gpForwardLogDetail;
            for (GpForwardLogDetailAdd gpForwardLogDetailAdd : gpForwardLogAdd.getForwardLogDetailAddList()) {
                gpForwardLogDetail = Convert.convert(new TypeReference<GpForwardLogDetail>() {}, gpForwardLogDetailAdd);
                gpForwardLogDetail.setForwardLogId(gpForwardLog.getId());
                gpForwardLogDetail.setAnnex(String.join(",", gpForwardLogDetailAdd.getAnnexList()));
                // 更新转发状态
                GpOrder order = iGpOrderService.getById(gpForwardLogDetail.getOrderId());
                if (order == null) {
                    continue;
                }
                if (gpForwardLogAdd.getIsForwardImg() != null && gpForwardLogAdd.getIsForwardImg() == 1) {
                    order.setIsForwardImg(1);
                }
                if (gpForwardLogAdd.getIsForwardVideo() != null && gpForwardLogAdd.getIsForwardVideo() == 1) {
                    order.setIsForwardVideo(1);
                }
                if ((order.getIsForwardImg() == 1 && order.getIsForwardVideo() == 1) || (gpForwardLogAdd.getIsForward() != null && gpForwardLogAdd.getIsForward() == 1)) {
                    order.setIsForward(1);
                }
                iGpOrderService.updateById(order);
                forwardLogDetailList.add(gpForwardLogDetail);
            }
            iGpForwardLogDetailService.saveBatch(forwardLogDetailList);
        }
        if (save) {
            return AjaxResult.success(gpForwardLog);
        } else {
            return AjaxResult.error("发送失败，请联系管理员");
        }
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLog
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/forwardLog")
    public AjaxResult forwardLogEdit(@Valid @RequestBody GpForwardLogUpdate gpForwardLogUpdate) {
        GpForwardLog gpForwardLog = Convert.convert(new TypeReference<GpForwardLog>() {}, gpForwardLogUpdate);
        return toAjax(iGpForwardLogService.updateById(gpForwardLog) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLog
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/forwardLog/{ids}" )
    public AjaxResult forwardLogRemove(@PathVariable Long[] ids) {
        return toAjax(iGpForwardLogService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 转发记录 forwardLog end **/

    /** 转发记录详情 forwardLogDetail begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLogDetail
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/forwardLogDetail/list")
    public TableDataInfo<GpForwardLogDetailVo> forwardLogDetailList(GpForwardLogDetailReq gpForwardLogDetailReq)
    {
        startPage();
        QueryWrapper<GpForwardLogDetail> lqw = new QueryWrapper<GpForwardLogDetail>();
        gpForwardLogDetailReq.generatorQuery(lqw,true);
        List<GpForwardLogDetailVo> list = iGpForwardLogDetailService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLogDetail
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/forwardLogDetail/{id}" )
    public AjaxResult<GpForwardLogDetailVo> forwardLogDetailGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpForwardLogDetailService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLogDetail
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/forwardLogDetail")
    public AjaxResult forwardLogDetailAdd(@Valid @RequestBody GpForwardLogDetailAdd gpForwardLogDetailAdd) {
        GpForwardLogDetail gpForwardLogDetail = Convert.convert(new TypeReference<GpForwardLogDetail>() {}, gpForwardLogDetailAdd);
        return toAjax(iGpForwardLogDetailService.save(gpForwardLogDetail) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLogDetail
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/forwardLogDetail")
    public AjaxResult forwardLogDetailEdit(@Valid @RequestBody GpForwardLogDetailUpdate gpForwardLogDetailUpdate) {
        GpForwardLogDetail gpForwardLogDetail = Convert.convert(new TypeReference<GpForwardLogDetail>() {}, gpForwardLogDetailUpdate);
        return toAjax(iGpForwardLogDetailService.updateById(gpForwardLogDetail) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpForwardLogDetail
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/forwardLogDetail/{ids}" )
    public AjaxResult forwardLogDetailRemove(@PathVariable Long[] ids) {
        return toAjax(iGpForwardLogDetailService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 转发记录详情 forwardLogDetail end **/

    /** 员工订单流转详情 orderFlow begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderFlow
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/orderFlow/list")
    public TableDataInfo<GpOrderFlowVo> orderFlowList(GpOrderFlowReq gpOrderFlowReq)
    {
        startPage();
        QueryWrapper<GpOrderFlow> lqw = new QueryWrapper<GpOrderFlow>();
        gpOrderFlowReq.generatorQuery(lqw,true);
        List<GpOrderFlowVo> list = iGpOrderFlowService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderFlow
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/orderFlow/{id}" )
    public AjaxResult<GpOrderFlowVo> orderFlowGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpOrderFlowService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderFlow
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/orderFlow")
    public AjaxResult orderFlowAdd(@Valid @RequestBody GpOrderFlowAdd gpOrderFlowAdd) {
        GpOrderFlow gpOrderFlow = Convert.convert(new TypeReference<GpOrderFlow>() {}, gpOrderFlowAdd);
        return toAjax(iGpOrderFlowService.save(gpOrderFlow) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderFlow
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/orderFlow")
    public AjaxResult orderFlowEdit(@Valid @RequestBody GpOrderFlowUpdate gpOrderFlowUpdate) {
        GpOrderFlow gpOrderFlow = Convert.convert(new TypeReference<GpOrderFlow>() {}, gpOrderFlowUpdate);
        return toAjax(iGpOrderFlowService.updateById(gpOrderFlow) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderFlow
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/orderFlow/{ids}" )
    public AjaxResult orderFlowRemove(@PathVariable Long[] ids) {
        return toAjax(iGpOrderFlowService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * @Description 确认
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("确认")
    @PostMapping("/order/orderFlow/confirm")
    public AjaxResult orderFlowConfirm(@Valid @RequestBody GpOrderFlowUpdate gpOrderFlowUpdate) {
        String confirm = iGpOrderFlowService.confirm(gpOrderFlowUpdate);
        if (StringUtils.isNotBlank(confirm)) {
            return AjaxResult.error(510, confirm);
        }
        return AjaxResult.success();
    }

    /**
     * @Description 撤回
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("撤回")
    @PostMapping("/order/orderFlow/withdraw")
    public AjaxResult orderFlowWithdraw(@Valid @RequestBody GpOrderFlowUpdate gpOrderFlowUpdate) {
        String withdraw = iGpOrderFlowService.withdraw(gpOrderFlowUpdate);
        if (StringUtils.isNotBlank(withdraw)) {
            return AjaxResult.error(510, withdraw);
        }
        return AjaxResult.success();
    }

    /**
     * @Description 中转
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("中转")
    @PostMapping("/order/orderFlow/transfer")
    public AjaxResult orderFlowTransfer(@Valid @RequestBody GpOrderFlowUpdate gpOrderFlowUpdate) {
        String transfer = iGpOrderFlowService.transfer(gpOrderFlowUpdate);
        if (StringUtils.isNotBlank(transfer)) {
            return AjaxResult.error(510, transfer);
        }
        return AjaxResult.success();
    }

    /**
     * @Description 附件上传（物流单/自提）
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrder
     * @Return AjaxResult
     */
    @ApiOperation("附件上传（物流单/自提）")
    @PostMapping("/order/orderFlow/uploadAnnex")
    public AjaxResult orderFlowUploadAnnex(@Valid @RequestBody GpOrderFlowUpdate gpOrderFlowUpdate) {
        GpOrderFlow gpOrderFlow = iGpOrderFlowService.getById(gpOrderFlowUpdate.getId());
        if (gpOrderFlow == null) {
            return AjaxResult.error("订单不存在");
        }
        List<String> annexList = gpOrderFlowUpdate.getAnnexList();
        if (CollectionUtils.isNotEmpty(annexList)) {
            gpOrderFlow.setAnnex(String.join(",", annexList));
        }
        gpOrderFlow.setStatus(gpOrderFlowUpdate.getStatus());
        gpOrderFlow.setUploadTime(new Date());
        iGpOrderFlowService.updateById(gpOrderFlow);
        if (StringUtils.equals(gpOrderFlow.getDestinationType(), DestinationTypeEnum.LOGISTICS.getKey())) {
            // 如果选择物流，需要流转至‘完成’
            GpOrder gpOrder = iGpOrderService.getById(gpOrderFlow.getOrderId());
            if (gpOrder != null && StringUtils.equals(gpOrder.getOrderStatus(), OrderStatusEnum.IN_TRANSIT_DELIVERY.getKey())) {
                UpdateWrapper<GpOrder> orderUpdateLqw = new UpdateWrapper<>();
                orderUpdateLqw.set("version", gpOrder.getVersion() + 1).eq("version", gpOrder.getVersion()).eq("id", gpOrder.getId());
                orderUpdateLqw.set("order_status", OrderStatusEnum.COMPLETE.getKey());
                orderUpdateLqw.set("order_duration", DateUtils.getDateMinDiff(new Date(), gpOrder.getCreateTime()));
                orderUpdateLqw.eq("id", gpOrder.getId());
                iGpOrderService.update(orderUpdateLqw);
            }
        }
        return AjaxResult.success();
    }

    /** 员工订单流转详情 orderFlow end **/

    /** 消息通知 orderNotify begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderNotify
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/orderNotify/list")
    public TableDataInfo<GpOrderNotifyVo> orderNotifyList(GpOrderNotifyReq gpOrderNotifyReq)
    {
        startPage();
        QueryWrapper<GpOrderNotify> lqw = new QueryWrapper<GpOrderNotify>();
        gpOrderNotifyReq.generatorQuery(lqw,true);
        lqw.orderByDesc("gp.update_time");
        List<GpOrderNotifyVo> list = iGpOrderNotifyService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderNotify
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/orderNotify/{id}" )
    public AjaxResult<GpOrderNotifyVo> orderNotifyGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpOrderNotifyService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderNotify
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/orderNotify")
    public AjaxResult orderNotifyAdd(@Valid @RequestBody GpOrderNotifyAdd gpOrderNotifyAdd) {
        GpOrderNotify gpOrderNotify = Convert.convert(new TypeReference<GpOrderNotify>() {}, gpOrderNotifyAdd);
        return toAjax(iGpOrderNotifyService.save(gpOrderNotify) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderNotify
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/orderNotify")
    public AjaxResult orderNotifyEdit(@Valid @RequestBody GpOrderNotifyUpdate gpOrderNotifyUpdate) {
        GpOrderNotify gpOrderNotify = Convert.convert(new TypeReference<GpOrderNotify>() {}, gpOrderNotifyUpdate);
        return toAjax(iGpOrderNotifyService.updateById(gpOrderNotify) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpOrderNotify
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/orderNotify/{ids}" )
    public AjaxResult orderNotifyRemove(@PathVariable Long[] ids) {
        return toAjax(iGpOrderNotifyService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 消息通知 orderNotify end **/

    /** 产品 product begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProduct
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/product/list")
    public TableDataInfo<GpProductVo> productList(GpProductReq gpProductReq)
    {
        startPage();
        QueryWrapper<GpProduct> lqw = new QueryWrapper<GpProduct>();
        gpProductReq.generatorQuery(lqw,true);
        List<GpProductVo> list = iGpProductService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProduct
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/product/{id}" )
    public AjaxResult<GpProductVo> productGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProductService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProduct
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/product")
    public AjaxResult productAdd(@Valid @RequestBody GpProductAdd gpProductAdd) {
        GpProduct gpProduct = Convert.convert(new TypeReference<GpProduct>() {}, gpProductAdd);
        return toAjax(iGpProductService.save(gpProduct) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProduct
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/product")
    public AjaxResult productEdit(@Valid @RequestBody GpProductUpdate gpProductUpdate) {
        GpProduct gpProduct = Convert.convert(new TypeReference<GpProduct>() {}, gpProductUpdate);
        return toAjax(iGpProductService.updateById(gpProduct) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProduct
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/product/{ids}" )
    public AjaxResult productRemove(@PathVariable Long[] ids) {
        return toAjax(iGpProductService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 产品 product end **/

    /** 产品详情 productDetails begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductDetails
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/productDetails/list")
    public TableDataInfo<GpProductDetailsVo> productDetailsList(GpProductDetailsReq gpProductDetailsReq)
    {
        startPage();
        QueryWrapper<GpProductDetails> lqw = new QueryWrapper<GpProductDetails>();
        gpProductDetailsReq.generatorQuery(lqw,true);
        List<GpProductDetailsVo> list = iGpProductDetailsService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductDetails
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/productDetails/{id}" )
    public AjaxResult<GpProductDetailsVo> productDetailsGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProductDetailsService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductDetails
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/productDetails")
    public AjaxResult productDetailsAdd(@Valid @RequestBody GpProductDetailsAdd gpProductDetailsAdd) {
        GpProductDetails gpProductDetails = Convert.convert(new TypeReference<GpProductDetails>() {}, gpProductDetailsAdd);
        return toAjax(iGpProductDetailsService.save(gpProductDetails) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductDetails
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/productDetails")
    public AjaxResult productDetailsEdit(@Valid @RequestBody GpProductDetailsUpdate gpProductDetailsUpdate) {
        GpProductDetails gpProductDetails = Convert.convert(new TypeReference<GpProductDetails>() {}, gpProductDetailsUpdate);
        return toAjax(iGpProductDetailsService.updateById(gpProductDetails) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductDetails
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/productDetails/{ids}" )
    public AjaxResult productDetailsRemove(@PathVariable Long[] ids) {
        return toAjax(iGpProductDetailsService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 产品详情 productDetails end **/

    /** 货架信息 productShelves begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/productShelves/list")
    public TableDataInfo<GpProductShelvesVo> productShelvesList(GpProductShelvesReq gpProductShelvesReq)
    {
        startPage();
        QueryWrapper<GpProductShelves> lqw = new QueryWrapper<GpProductShelves>();
        gpProductShelvesReq.generatorQuery(lqw,true);
        if (StringUtils.isNotBlank(gpProductShelvesReq.getProductName())) {
            lqw.eq("gp.product_name", gpProductShelvesReq.getProductName());
        }
        if (StringUtils.isNotBlank(gpProductShelvesReq.getSearchName())){
            lqw.and(wrapper -> wrapper.like("gp.colour" ,gpProductShelvesReq.getSearchName()).or().like("gp.shelf_number" ,gpProductShelvesReq.getSearchName()));
        }
        lqw.orderByAsc("gp.colour");
        lqw.orderByAsc("LENGTH(gp.colour)");
        List<GpProductShelvesVo> list = iGpProductShelvesService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 货架一级列表
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return TableDataInfo
     */
    @ApiOperation("货架一级列表")
    @GetMapping("/order/productShelves/productNameList")
    public TableDataInfo<GpProductShelvesVo> productNameList(GpProductShelvesReq gpProductShelvesReq)
    {
        startPage();
        QueryWrapper<GpProductShelves> lqw = new QueryWrapper<GpProductShelves>();
        gpProductShelvesReq.generatorQuery(lqw,true);
        if (StringUtils.isNotBlank(gpProductShelvesReq.getSearchName())){
            lqw.like("gp.product_name", gpProductShelvesReq.getSearchName());
        }
        lqw.groupBy("gp.product_name");
        lqw.orderByAsc("LENGTH(gp.product_name)");
        lqw.orderByAsc("gp.product_name");
        List<GpProductShelvesVo> list = iGpProductShelvesService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/productShelves/{id}" )
    public AjaxResult<GpProductShelvesVo> productShelvesGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProductShelvesService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/productShelves")
    public AjaxResult productShelvesAdd(@Valid @RequestBody GpProductShelvesAdd gpProductShelvesAdd) {
        GpProductShelves gpProductShelves = Convert.convert(new TypeReference<GpProductShelves>() {}, gpProductShelvesAdd);
        return toAjax(iGpProductShelvesService.save(gpProductShelves) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/productShelves")
    public AjaxResult productShelvesEdit(@Valid @RequestBody GpProductShelvesUpdate gpProductShelvesUpdate) {
        GpProductShelves gpProductShelves = Convert.convert(new TypeReference<GpProductShelves>() {}, gpProductShelvesUpdate);
        return toAjax(iGpProductShelvesService.updateById(gpProductShelves) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelves
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/productShelves/{ids}" )
    public AjaxResult productShelvesRemove(@PathVariable Long[] ids) {
        return toAjax(iGpProductShelvesService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 货架信息 productShelves end **/

    /** 货架图片信息 productShelvesImg begin **/

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelvesImg
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @GetMapping("/order/productShelvesImg/list")
    public TableDataInfo<GpProductShelvesImgVo> productShelvesImgList(GpProductShelvesImgReq gpProductShelvesImgReq)
    {
        startPage();
        QueryWrapper<GpProductShelvesImg> lqw = new QueryWrapper<GpProductShelvesImg>();
        gpProductShelvesImgReq.generatorQuery(lqw,true);
        List<GpProductShelvesImgVo> list = iGpProductShelvesImgService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelvesImg
     * @Return AjaxResult
     */
    @ApiOperation("详情")
    @GetMapping(value = "/order/productShelvesImg/{id}" )
    public AjaxResult<GpProductShelvesImgVo> productShelvesImgGetInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpProductShelvesImgService.getVoById(id));
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelvesImg
     * @Return AjaxResult
     */
    @ApiOperation("新增")
    @PostMapping("/order/productShelvesImg")
    public AjaxResult productShelvesImgAdd(@Valid @RequestBody GpProductShelvesImgAdd gpProductShelvesImgAdd) {
        GpProductShelvesImg gpProductShelvesImg = Convert.convert(new TypeReference<GpProductShelvesImg>() {}, gpProductShelvesImgAdd);
        return toAjax(iGpProductShelvesImgService.save(gpProductShelvesImg) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelvesImg
     * @Return AjaxResult
     */
    @ApiOperation("修改")
    @PutMapping("/order/productShelvesImg")
    public AjaxResult productShelvesImgEdit(@Valid @RequestBody GpProductShelvesImgUpdate gpProductShelvesImgUpdate) {
        GpProductShelvesImg gpProductShelvesImg = Convert.convert(new TypeReference<GpProductShelvesImg>() {}, gpProductShelvesImgUpdate);
        return toAjax(iGpProductShelvesImgService.updateById(gpProductShelvesImg) ? 1 : 0);
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-4-25
     * @Param gpProductShelvesImg
     * @Return AjaxResult
     */
    @ApiOperation("删除")
    @DeleteMapping("/order/productShelvesImg/{ids}" )
    public AjaxResult productShelvesImgRemove(@PathVariable Long[] ids) {
        return toAjax(iGpProductShelvesImgService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /** 货架图片信息 productShelvesImg end **/
}
